chiark / gitweb /
Update changelog for 20170923.ff218728-0+iwj2~3.gbpc58e0c release
[sgt-puzzles.git] / pearl.c
1 /*
2  * pearl.c: Nikoli's `Masyu' puzzle. 
3  */
4
5 /*
6  * TODO:
7  *
8  *  - The current keyboard cursor mechanism works well on ordinary PC
9  *    keyboards, but for platforms with only arrow keys and a select
10  *    button or two, we may at some point need a simpler one which can
11  *    handle 'x' markings without needing shift keys. For instance, a
12  *    cursor with twice the grid resolution, so that it can range
13  *    across face centres, edge centres and vertices; 'clicks' on face
14  *    centres begin a drag as currently, clicks on edges toggle
15  *    markings, and clicks on vertices are ignored (but it would be
16  *    too confusing not to let the cursor rest on them). But I'm
17  *    pretty sure that would be less pleasant to play on a full
18  *    keyboard, so probably a #ifdef would be the thing.
19  *
20  *  - Generation is still pretty slow, due to difficulty coming up in
21  *    the first place with a loop that makes a soluble puzzle even
22  *    with all possible clues filled in.
23  *     + A possible alternative strategy to further tuning of the
24  *       existing loop generator would be to throw the entire
25  *       mechanism out and instead write a different generator from
26  *       scratch which evolves the solution along with the puzzle:
27  *       place a few clues, nail down a bit of the loop, place another
28  *       clue, nail down some more, etc. However, I don't have a
29  *       detailed plan for any such mechanism, so it may be a pipe
30  *       dream.
31  */
32
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <assert.h>
37 #include <ctype.h>
38 #include <math.h>
39
40 #include "puzzles.h"
41 #include "grid.h"
42 #include "loopgen.h"
43
44 #define SWAP(i,j) do { int swaptmp = (i); (i) = (j); (j) = swaptmp; } while (0)
45
46 #define NOCLUE 0
47 #define CORNER 1
48 #define STRAIGHT 2
49
50 #define R 1
51 #define U 2
52 #define L 4
53 #define D 8
54
55 #define DX(d) ( ((d)==R) - ((d)==L) )
56 #define DY(d) ( ((d)==D) - ((d)==U) )
57
58 #define F(d) (((d << 2) | (d >> 2)) & 0xF)
59 #define C(d) (((d << 3) | (d >> 1)) & 0xF)
60 #define A(d) (((d << 1) | (d >> 3)) & 0xF)
61
62 #define LR (L | R)
63 #define RL (R | L)
64 #define UD (U | D)
65 #define DU (D | U)
66 #define LU (L | U)
67 #define UL (U | L)
68 #define LD (L | D)
69 #define DL (D | L)
70 #define RU (R | U)
71 #define UR (U | R)
72 #define RD (R | D)
73 #define DR (D | R)
74 #define BLANK 0
75 #define UNKNOWN 15
76
77 #define bLR (1 << LR)
78 #define bRL (1 << RL)
79 #define bUD (1 << UD)
80 #define bDU (1 << DU)
81 #define bLU (1 << LU)
82 #define bUL (1 << UL)
83 #define bLD (1 << LD)
84 #define bDL (1 << DL)
85 #define bRU (1 << RU)
86 #define bUR (1 << UR)
87 #define bRD (1 << RD)
88 #define bDR (1 << DR)
89 #define bBLANK (1 << BLANK)
90
91 enum {
92     COL_BACKGROUND, COL_HIGHLIGHT, COL_LOWLIGHT,
93     COL_CURSOR_BACKGROUND = COL_LOWLIGHT,
94     COL_BLACK, COL_WHITE,
95     COL_ERROR, COL_GRID, COL_FLASH,
96     COL_DRAGON, COL_DRAGOFF,
97     NCOLOURS
98 };
99
100 /* Macro ickery copied from slant.c */
101 #define DIFFLIST(A) \
102     A(EASY,Easy,e) \
103     A(TRICKY,Tricky,t)
104 #define ENUM(upper,title,lower) DIFF_ ## upper,
105 #define TITLE(upper,title,lower) #title,
106 #define ENCODE(upper,title,lower) #lower
107 #define CONFIG(upper,title,lower) ":" #title
108 enum { DIFFLIST(ENUM) DIFFCOUNT };
109 static char const *const pearl_diffnames[] = { DIFFLIST(TITLE) "(count)" };
110 static char const pearl_diffchars[] = DIFFLIST(ENCODE);
111 #define DIFFCONFIG DIFFLIST(CONFIG)
112
113 struct game_params {
114     int w, h;
115     int difficulty;
116     int nosolve;        /* XXX remove me! */
117 };
118
119 struct shared_state {
120     int w, h, sz;
121     char *clues;         /* size w*h */
122     int refcnt;
123 };
124
125 #define INGRID(state, gx, gy) ((gx) >= 0 && (gx) < (state)->shared->w && \
126                                (gy) >= 0 && (gy) < (state)->shared->h)
127 struct game_state {
128     struct shared_state *shared;
129     char *lines;        /* size w*h: lines placed */
130     char *errors;       /* size w*h: errors detected */
131     char *marks;        /* size w*h: 'no line here' marks placed. */
132     int completed, used_solve;
133 };
134
135 #define DEFAULT_PRESET 3
136
137 static const struct game_params pearl_presets[] = {
138     {6, 6,      DIFF_EASY},
139     {6, 6,      DIFF_TRICKY},
140     {8, 8,      DIFF_EASY},
141     {8, 8,      DIFF_TRICKY},
142     {10, 10,    DIFF_EASY},
143     {10, 10,    DIFF_TRICKY},
144     {12, 8,     DIFF_EASY},
145     {12, 8,     DIFF_TRICKY},
146 };
147
148 static game_params *default_params(void)
149 {
150     game_params *ret = snew(game_params);
151
152     *ret = pearl_presets[DEFAULT_PRESET];
153     ret->nosolve = FALSE;
154
155     return ret;
156 }
157
158 static int game_fetch_preset(int i, char **name, game_params **params)
159 {
160     game_params *ret;
161     char buf[64];
162
163     if (i < 0 || i >= lenof(pearl_presets)) return FALSE;
164
165     ret = default_params();
166     *ret = pearl_presets[i]; /* struct copy */
167     *params = ret;
168
169     sprintf(buf, "%dx%d %s",
170             pearl_presets[i].w, pearl_presets[i].h,
171             pearl_diffnames[pearl_presets[i].difficulty]);
172     *name = dupstr(buf);
173
174     return TRUE;
175 }
176
177 static void free_params(game_params *params)
178 {
179     sfree(params);
180 }
181
182 static game_params *dup_params(const game_params *params)
183 {
184     game_params *ret = snew(game_params);
185     *ret = *params;                    /* structure copy */
186     return ret;
187 }
188
189 static void decode_params(game_params *ret, char const *string)
190 {
191     ret->w = ret->h = atoi(string);
192     while (*string && isdigit((unsigned char) *string)) ++string;
193     if (*string == 'x') {
194         string++;
195         ret->h = atoi(string);
196         while (*string && isdigit((unsigned char)*string)) string++;
197     }
198
199     ret->difficulty = DIFF_EASY;
200     if (*string == 'd') {
201         int i;
202         string++;
203         for (i = 0; i < DIFFCOUNT; i++)
204             if (*string == pearl_diffchars[i])
205                 ret->difficulty = i;
206         if (*string) string++;
207     }
208
209     ret->nosolve = FALSE;
210     if (*string == 'n') {
211         ret->nosolve = TRUE;
212         string++;
213     }
214 }
215
216 static char *encode_params(const game_params *params, int full)
217 {
218     char buf[256];
219     sprintf(buf, "%dx%d", params->w, params->h);
220     if (full)
221         sprintf(buf + strlen(buf), "d%c%s",
222                 pearl_diffchars[params->difficulty],
223                 params->nosolve ? "n" : "");
224     return dupstr(buf);
225 }
226
227 static config_item *game_configure(const game_params *params)
228 {
229     config_item *ret;
230     char buf[64];
231
232     ret = snewn(5, config_item);
233
234     ret[0].name = "Width";
235     ret[0].type = C_STRING;
236     sprintf(buf, "%d", params->w);
237     ret[0].u.string.sval = dupstr(buf);
238
239     ret[1].name = "Height";
240     ret[1].type = C_STRING;
241     sprintf(buf, "%d", params->h);
242     ret[1].u.string.sval = dupstr(buf);
243
244     ret[2].name = "Difficulty";
245     ret[2].type = C_CHOICES;
246     ret[2].u.choices.choicenames = DIFFCONFIG;
247     ret[2].u.choices.selected = params->difficulty;
248
249     ret[3].name = "Allow unsoluble";
250     ret[3].type = C_BOOLEAN;
251     ret[3].u.boolean.bval = params->nosolve;
252
253     ret[4].name = NULL;
254     ret[4].type = C_END;
255
256     return ret;
257 }
258
259 static game_params *custom_params(const config_item *cfg)
260 {
261     game_params *ret = snew(game_params);
262
263     ret->w = atoi(cfg[0].u.string.sval);
264     ret->h = atoi(cfg[1].u.string.sval);
265     ret->difficulty = cfg[2].u.choices.selected;
266     ret->nosolve = cfg[3].u.boolean.bval;
267
268     return ret;
269 }
270
271 static const char *validate_params(const game_params *params, int full)
272 {
273     if (params->w < 5) return "Width must be at least five";
274     if (params->h < 5) return "Height must be at least five";
275     if (params->difficulty < 0 || params->difficulty >= DIFFCOUNT)
276         return "Unknown difficulty level";
277     if (params->difficulty >= DIFF_TRICKY && params->w + params->h < 11)
278         return "Width or height must be at least six for Tricky";
279
280     return NULL;
281 }
282
283 /* ----------------------------------------------------------------------
284  * Solver.
285  */
286
287 int pearl_solve(int w, int h, char *clues, char *result,
288                 int difficulty, int partial)
289 {
290     int W = 2*w+1, H = 2*h+1;
291     short *workspace;
292     int *dsf, *dsfsize;
293     int x, y, b, d;
294     int ret = -1;
295
296     /*
297      * workspace[(2*y+1)*W+(2*x+1)] indicates the possible nature
298      * of the square (x,y), as a logical OR of bitfields.
299      * 
300      * workspace[(2*y)*W+(2*x+1)], for x odd and y even, indicates
301      * whether the horizontal edge between (x,y) and (x+1,y) is
302      * connected (1), disconnected (2) or unknown (3).
303      * 
304      * workspace[(2*y+1)*W+(2*x)], indicates the same about the
305      * vertical edge between (x,y) and (x,y+1).
306      * 
307      * Initially, every square is considered capable of being in
308      * any of the seven possible states (two straights, four
309      * corners and empty), except those corresponding to clue
310      * squares which are more restricted.
311      * 
312      * Initially, all edges are unknown, except the ones around the
313      * grid border which are known to be disconnected.
314      */
315     workspace = snewn(W*H, short);
316     for (x = 0; x < W*H; x++)
317         workspace[x] = 0;
318     /* Square states */
319     for (y = 0; y < h; y++)
320         for (x = 0; x < w; x++)
321             switch (clues[y*w+x]) {
322               case CORNER:
323                 workspace[(2*y+1)*W+(2*x+1)] = bLU|bLD|bRU|bRD;
324                 break;
325               case STRAIGHT:
326                 workspace[(2*y+1)*W+(2*x+1)] = bLR|bUD;
327                 break;
328               default:
329                 workspace[(2*y+1)*W+(2*x+1)] = bLR|bUD|bLU|bLD|bRU|bRD|bBLANK;
330                 break;
331             }
332     /* Horizontal edges */
333     for (y = 0; y <= h; y++)
334         for (x = 0; x < w; x++)
335             workspace[(2*y)*W+(2*x+1)] = (y==0 || y==h ? 2 : 3);
336     /* Vertical edges */
337     for (y = 0; y < h; y++)
338         for (x = 0; x <= w; x++)
339             workspace[(2*y+1)*W+(2*x)] = (x==0 || x==w ? 2 : 3);
340
341     /*
342      * We maintain a dsf of connected squares, together with a
343      * count of the size of each equivalence class.
344      */
345     dsf = snewn(w*h, int);
346     dsfsize = snewn(w*h, int);
347
348     /*
349      * Now repeatedly try to find something we can do.
350      */
351     while (1) {
352         int done_something = FALSE;
353
354 #ifdef SOLVER_DIAGNOSTICS
355         for (y = 0; y < H; y++) {
356             for (x = 0; x < W; x++)
357                 printf("%*x", (x&1) ? 5 : 2, workspace[y*W+x]);
358             printf("\n");
359         }
360 #endif
361
362         /*
363          * Go through the square state words, and discard any
364          * square state which is inconsistent with known facts
365          * about the edges around the square.
366          */
367         for (y = 0; y < h; y++)
368             for (x = 0; x < w; x++) {
369                 for (b = 0; b < 0xD; b++)
370                     if (workspace[(2*y+1)*W+(2*x+1)] & (1<<b)) {
371                         /*
372                          * If any edge of this square is known to
373                          * be connected when state b would require
374                          * it disconnected, or vice versa, discard
375                          * the state.
376                          */
377                         for (d = 1; d <= 8; d += d) {
378                             int ex = 2*x+1 + DX(d), ey = 2*y+1 + DY(d);
379                             if (workspace[ey*W+ex] ==
380                                 ((b & d) ? 2 : 1)) {
381                                 workspace[(2*y+1)*W+(2*x+1)] &= ~(1<<b);
382 #ifdef SOLVER_DIAGNOSTICS
383                                 printf("edge (%d,%d)-(%d,%d) rules out state"
384                                        " %d for square (%d,%d)\n",
385                                        ex/2, ey/2, (ex+1)/2, (ey+1)/2,
386                                        b, x, y);
387 #endif
388                                 done_something = TRUE;
389                                 break;
390                             }
391                         }
392                     }
393
394                 /*
395                  * Consistency check: each square must have at
396                  * least one state left!
397                  */
398                 if (!workspace[(2*y+1)*W+(2*x+1)]) {
399 #ifdef SOLVER_DIAGNOSTICS
400                     printf("edge check at (%d,%d): inconsistency\n", x, y);
401 #endif
402                     ret = 0;
403                     goto cleanup;
404                 }
405             }
406
407         /*
408          * Now go through the states array again, and nail down any
409          * unknown edge if one of its neighbouring squares makes it
410          * known.
411          */
412         for (y = 0; y < h; y++)
413             for (x = 0; x < w; x++) {
414                 int edgeor = 0, edgeand = 15;
415
416                 for (b = 0; b < 0xD; b++)
417                     if (workspace[(2*y+1)*W+(2*x+1)] & (1<<b)) {
418                         edgeor |= b;
419                         edgeand &= b;
420                     }
421
422                 /*
423                  * Now any bit clear in edgeor marks a disconnected
424                  * edge, and any bit set in edgeand marks a
425                  * connected edge.
426                  */
427
428                 /* First check consistency: neither bit is both! */
429                 if (edgeand & ~edgeor) {
430 #ifdef SOLVER_DIAGNOSTICS
431                     printf("square check at (%d,%d): inconsistency\n", x, y);
432 #endif
433                     ret = 0;
434                     goto cleanup;
435                 }
436
437                 for (d = 1; d <= 8; d += d) {
438                     int ex = 2*x+1 + DX(d), ey = 2*y+1 + DY(d);
439
440                     if (!(edgeor & d) && workspace[ey*W+ex] == 3) {
441                         workspace[ey*W+ex] = 2;
442                         done_something = TRUE;
443 #ifdef SOLVER_DIAGNOSTICS
444                         printf("possible states of square (%d,%d) force edge"
445                                " (%d,%d)-(%d,%d) to be disconnected\n",
446                                x, y, ex/2, ey/2, (ex+1)/2, (ey+1)/2);
447 #endif
448                     } else if ((edgeand & d) && workspace[ey*W+ex] == 3) {
449                         workspace[ey*W+ex] = 1;
450                         done_something = TRUE;
451 #ifdef SOLVER_DIAGNOSTICS
452                         printf("possible states of square (%d,%d) force edge"
453                                " (%d,%d)-(%d,%d) to be connected\n",
454                                x, y, ex/2, ey/2, (ex+1)/2, (ey+1)/2);
455 #endif
456                     }
457                 }
458             }
459
460         if (done_something)
461             continue;
462
463         /*
464          * Now for longer-range clue-based deductions (using the
465          * rules that a corner clue must connect to two straight
466          * squares, and a straight clue must connect to at least
467          * one corner square).
468          */
469         for (y = 0; y < h; y++)
470             for (x = 0; x < w; x++)
471                 switch (clues[y*w+x]) {
472                   case CORNER:
473                     for (d = 1; d <= 8; d += d) {
474                         int ex = 2*x+1 + DX(d), ey = 2*y+1 + DY(d);
475                         int fx = ex + DX(d), fy = ey + DY(d);
476                         int type = d | F(d);
477
478                         if (workspace[ey*W+ex] == 1) {
479                             /*
480                              * If a corner clue is connected on any
481                              * edge, then we can immediately nail
482                              * down the square beyond that edge as
483                              * being a straight in the appropriate
484                              * direction.
485                              */
486                             if (workspace[fy*W+fx] != (1<<type)) {
487                                 workspace[fy*W+fx] = (1<<type);
488                                 done_something = TRUE;
489 #ifdef SOLVER_DIAGNOSTICS
490                                 printf("corner clue at (%d,%d) forces square "
491                                        "(%d,%d) into state %d\n", x, y,
492                                        fx/2, fy/2, type);
493 #endif
494                                 
495                             }
496                         } else if (workspace[ey*W+ex] == 3) {
497                             /*
498                              * Conversely, if a corner clue is
499                              * separated by an unknown edge from a
500                              * square which _cannot_ be a straight
501                              * in the appropriate direction, we can
502                              * mark that edge as disconnected.
503                              */
504                             if (!(workspace[fy*W+fx] & (1<<type))) {
505                                 workspace[ey*W+ex] = 2;
506                                 done_something = TRUE;
507 #ifdef SOLVER_DIAGNOSTICS
508                                 printf("corner clue at (%d,%d), plus square "
509                                        "(%d,%d) not being state %d, "
510                                        "disconnects edge (%d,%d)-(%d,%d)\n",
511                                        x, y, fx/2, fy/2, type,
512                                        ex/2, ey/2, (ex+1)/2, (ey+1)/2);
513 #endif
514
515                             }
516                         }
517                     }
518
519                     break;
520                   case STRAIGHT:
521                     /*
522                      * If a straight clue is between two squares
523                      * neither of which is capable of being a
524                      * corner connected to it, then the straight
525                      * clue cannot point in that direction.
526                      */
527                     for (d = 1; d <= 2; d += d) {
528                         int fx = 2*x+1 + 2*DX(d), fy = 2*y+1 + 2*DY(d);
529                         int gx = 2*x+1 - 2*DX(d), gy = 2*y+1 - 2*DY(d);
530                         int type = d | F(d);
531
532                         if (!(workspace[(2*y+1)*W+(2*x+1)] & (1<<type)))
533                             continue;
534
535                         if (!(workspace[fy*W+fx] & ((1<<(F(d)|A(d))) |
536                                                     (1<<(F(d)|C(d))))) &&
537                             !(workspace[gy*W+gx] & ((1<<(  d |A(d))) |
538                                                     (1<<(  d |C(d)))))) {
539                             workspace[(2*y+1)*W+(2*x+1)] &= ~(1<<type);
540                             done_something = TRUE;
541 #ifdef SOLVER_DIAGNOSTICS
542                             printf("straight clue at (%d,%d) cannot corner at "
543                                    "(%d,%d) or (%d,%d) so is not state %d\n",
544                                    x, y, fx/2, fy/2, gx/2, gy/2, type);
545 #endif
546                         }
547                                                     
548                     }
549
550                     /*
551                      * If a straight clue with known direction is
552                      * connected on one side to a known straight,
553                      * then on the other side it must be a corner.
554                      */
555                     for (d = 1; d <= 8; d += d) {
556                         int fx = 2*x+1 + 2*DX(d), fy = 2*y+1 + 2*DY(d);
557                         int gx = 2*x+1 - 2*DX(d), gy = 2*y+1 - 2*DY(d);
558                         int type = d | F(d);
559
560                         if (workspace[(2*y+1)*W+(2*x+1)] != (1<<type))
561                             continue;
562
563                         if (!(workspace[fy*W+fx] &~ (bLR|bUD)) &&
564                             (workspace[gy*W+gx] &~ (bLU|bLD|bRU|bRD))) {
565                             workspace[gy*W+gx] &= (bLU|bLD|bRU|bRD);
566                             done_something = TRUE;
567 #ifdef SOLVER_DIAGNOSTICS
568                             printf("straight clue at (%d,%d) connecting to "
569                                    "straight at (%d,%d) makes (%d,%d) a "
570                                    "corner\n", x, y, fx/2, fy/2, gx/2, gy/2);
571 #endif
572                         }
573                                                     
574                     }
575                     break;
576                 }
577
578         if (done_something)
579             continue;
580
581         /*
582          * Now detect shortcut loops.
583          */
584
585         {
586             int nonblanks, loopclass;
587
588             dsf_init(dsf, w*h);
589             for (x = 0; x < w*h; x++)
590                 dsfsize[x] = 1;
591
592             /*
593              * First go through the edge entries and update the dsf
594              * of which squares are connected to which others. We
595              * also track the number of squares in each equivalence
596              * class, and count the overall number of
597              * known-non-blank squares.
598              *
599              * In the process of doing this, we must notice if a
600              * loop has already been formed. If it has, we blank
601              * out any square which isn't part of that loop
602              * (failing a consistency check if any such square does
603              * not have BLANK as one of its remaining options) and
604              * exit the deduction loop with success.
605              */
606             nonblanks = 0;
607             loopclass = -1;
608             for (y = 1; y < H-1; y++)
609                 for (x = 1; x < W-1; x++)
610                     if ((y ^ x) & 1) {
611                         /*
612                          * (x,y) are the workspace coordinates of
613                          * an edge field. Compute the normal-space
614                          * coordinates of the squares it connects.
615                          */
616                         int ax = (x-1)/2, ay = (y-1)/2, ac = ay*w+ax;
617                         int bx = x/2, by = y/2, bc = by*w+bx;
618
619                         /*
620                          * If the edge is connected, do the dsf
621                          * thing.
622                          */
623                         if (workspace[y*W+x] == 1) {
624                             int ae, be;
625
626                             ae = dsf_canonify(dsf, ac);
627                             be = dsf_canonify(dsf, bc);
628
629                             if (ae == be) {
630                                 /*
631                                  * We have a loop!
632                                  */
633                                 if (loopclass != -1) {
634                                     /*
635                                      * In fact, we have two
636                                      * separate loops, which is
637                                      * doom.
638                                      */
639 #ifdef SOLVER_DIAGNOSTICS
640                                     printf("two loops found in grid!\n");
641 #endif
642                                     ret = 0;
643                                     goto cleanup;
644                                 }
645                                 loopclass = ae;
646                             } else {
647                                 /*
648                                  * Merge the two equivalence
649                                  * classes.
650                                  */
651                                 int size = dsfsize[ae] + dsfsize[be];
652                                 dsf_merge(dsf, ac, bc);
653                                 ae = dsf_canonify(dsf, ac);
654                                 dsfsize[ae] = size;
655                             }
656                         }
657                     } else if ((y & x) & 1) {
658                         /*
659                          * (x,y) are the workspace coordinates of a
660                          * square field. If the square is
661                          * definitely not blank, count it.
662                          */
663                         if (!(workspace[y*W+x] & bBLANK))
664                             nonblanks++;
665                     }
666
667             /*
668              * If we discovered an existing loop above, we must now
669              * blank every square not part of it, and exit the main
670              * deduction loop.
671              */
672             if (loopclass != -1) {
673 #ifdef SOLVER_DIAGNOSTICS
674                 printf("loop found in grid!\n");
675 #endif
676                 for (y = 0; y < h; y++)
677                     for (x = 0; x < w; x++)
678                         if (dsf_canonify(dsf, y*w+x) != loopclass) {
679                             if (workspace[(y*2+1)*W+(x*2+1)] & bBLANK) {
680                                 workspace[(y*2+1)*W+(x*2+1)] = bBLANK;
681                             } else {
682                                 /*
683                                  * This square is not part of the
684                                  * loop, but is known non-blank. We
685                                  * have goofed.
686                                  */
687 #ifdef SOLVER_DIAGNOSTICS
688                                 printf("non-blank square (%d,%d) found outside"
689                                        " loop!\n", x, y);
690 #endif
691                                 ret = 0;
692                                 goto cleanup;
693                             }
694                         }
695                 /*
696                  * And we're done.
697                  */
698                 ret = 1;
699                 break;
700             }
701
702             /* Further deductions are considered 'tricky'. */
703             if (difficulty == DIFF_EASY) goto done_deductions;
704
705             /*
706              * Now go through the workspace again and mark any edge
707              * which would cause a shortcut loop (i.e. would
708              * connect together two squares in the same equivalence
709              * class, and that equivalence class does not contain
710              * _all_ the known-non-blank squares currently in the
711              * grid) as disconnected. Also, mark any _square state_
712              * which would cause a shortcut loop as disconnected.
713              */
714             for (y = 1; y < H-1; y++)
715                 for (x = 1; x < W-1; x++)
716                     if ((y ^ x) & 1) {
717                         /*
718                          * (x,y) are the workspace coordinates of
719                          * an edge field. Compute the normal-space
720                          * coordinates of the squares it connects.
721                          */
722                         int ax = (x-1)/2, ay = (y-1)/2, ac = ay*w+ax;
723                         int bx = x/2, by = y/2, bc = by*w+bx;
724
725                         /*
726                          * If the edge is currently unknown, and
727                          * sits between two squares in the same
728                          * equivalence class, and the size of that
729                          * class is less than nonblanks, then
730                          * connecting this edge would be a shortcut
731                          * loop and so we must not do so.
732                          */
733                         if (workspace[y*W+x] == 3) {
734                             int ae, be;
735
736                             ae = dsf_canonify(dsf, ac);
737                             be = dsf_canonify(dsf, bc);
738
739                             if (ae == be) {
740                                 /*
741                                  * We have a loop. Is it a shortcut?
742                                  */
743                                 if (dsfsize[ae] < nonblanks) {
744                                     /*
745                                      * Yes! Mark this edge disconnected.
746                                      */
747                                     workspace[y*W+x] = 2;
748                                     done_something = TRUE;
749 #ifdef SOLVER_DIAGNOSTICS
750                                     printf("edge (%d,%d)-(%d,%d) would create"
751                                            " a shortcut loop, hence must be"
752                                            " disconnected\n", x/2, y/2,
753                                            (x+1)/2, (y+1)/2);
754 #endif
755                                 }
756                             }
757                         }
758                     } else if ((y & x) & 1) {
759                         /*
760                          * (x,y) are the workspace coordinates of a
761                          * square field. Go through its possible
762                          * (non-blank) states and see if any gives
763                          * rise to a shortcut loop.
764                          * 
765                          * This is slightly fiddly, because we have
766                          * to check whether this square is already
767                          * part of the same equivalence class as
768                          * the things it's joining.
769                          */
770                         int ae = dsf_canonify(dsf, (y/2)*w+(x/2));
771
772                         for (b = 2; b < 0xD; b++)
773                             if (workspace[y*W+x] & (1<<b)) {
774                                 /*
775                                  * Find the equivalence classes of
776                                  * the two squares this one would
777                                  * connect if it were in this
778                                  * state.
779                                  */
780                                 int e = -1;
781
782                                 for (d = 1; d <= 8; d += d) if (b & d) {
783                                     int xx = x/2 + DX(d), yy = y/2 + DY(d);
784                                     int ee = dsf_canonify(dsf, yy*w+xx);
785
786                                     if (e == -1)
787                                         ee = e;
788                                     else if (e != ee)
789                                         e = -2;
790                                 }
791
792                                 if (e >= 0) {
793                                     /*
794                                      * This square state would form
795                                      * a loop on equivalence class
796                                      * e. Measure the size of that
797                                      * loop, and see if it's a
798                                      * shortcut.
799                                      */
800                                     int loopsize = dsfsize[e];
801                                     if (e != ae)
802                                         loopsize++;/* add the square itself */
803                                     if (loopsize < nonblanks) {
804                                         /*
805                                          * It is! Mark this square
806                                          * state invalid.
807                                          */
808                                         workspace[y*W+x] &= ~(1<<b);
809                                         done_something = TRUE;
810 #ifdef SOLVER_DIAGNOSTICS
811                                         printf("square (%d,%d) would create a "
812                                                "shortcut loop in state %d, "
813                                                "hence cannot be\n",
814                                                x/2, y/2, b);
815 #endif
816                                     }
817                                 }
818                             }
819                     }
820         }
821
822 done_deductions:
823
824         if (done_something)
825             continue;
826
827         /*
828          * If we reach here, there is nothing left we can do.
829          * Return 2 for ambiguous puzzle.
830          */
831         ret = 2;
832         break;
833     }
834
835 cleanup:
836
837     /*
838      * If ret = 1 then we've successfully achieved a solution. This
839      * means that we expect every square to be nailed down to
840      * exactly one possibility. If this is the case, or if the caller
841      * asked for a partial solution anyway, transcribe those
842      * possibilities into the result array.
843      */
844     if (ret == 1 || partial) {
845         for (y = 0; y < h; y++) {
846             for (x = 0; x < w; x++) {
847                 for (b = 0; b < 0xD; b++)
848                     if (workspace[(2*y+1)*W+(2*x+1)] == (1<<b)) {
849                         result[y*w+x] = b;
850                         break;
851                     }
852                if (ret == 1) assert(b < 0xD); /* we should have had a break by now */
853             }
854         }
855     }
856
857     sfree(dsfsize);
858     sfree(dsf);
859     sfree(workspace);
860     assert(ret >= 0);
861     return ret;
862 }
863
864 /* ----------------------------------------------------------------------
865  * Loop generator.
866  */
867
868 /*
869  * We use the loop generator code from loopy, hard-coding to a square
870  * grid of the appropriate size. Knowing the grid layout and the tile
871  * size we can shrink that to our small grid and then make our line
872  * layout from the face colour info.
873  *
874  * We provide a bias function to the loop generator which tries to
875  * bias in favour of loops with more scope for Pearl black clues. This
876  * seems to improve the success rate of the puzzle generator, in that
877  * such loops have a better chance of being soluble with all valid
878  * clues put in.
879  */
880
881 struct pearl_loopgen_bias_ctx {
882     /*
883      * Our bias function counts the number of 'black clue' corners
884      * (i.e. corners adjacent to two straights) in both the
885      * BLACK/nonBLACK and WHITE/nonWHITE boundaries. In order to do
886      * this, we must:
887      *
888      *  - track the edges that are part of each of those loops
889      *  - track the types of vertex in each loop (corner, straight,
890      *    none)
891      *  - track the current black-clue status of each vertex in each
892      *    loop.
893      *
894      * Each of these chunks of data is updated incrementally from the
895      * previous one, to avoid slowdown due to the bias function
896      * rescanning the whole grid every time it's called.
897      *
898      * So we need a lot of separate arrays, plus a tdq for each one,
899      * and we must repeat it all twice for the BLACK and WHITE
900      * boundaries.
901      */
902     struct pearl_loopgen_bias_ctx_boundary {
903         int colour;                    /* FACE_WHITE or FACE_BLACK */
904
905         char *edges;                   /* is each edge part of the loop? */
906         tdq *edges_todo;
907
908         char *vertextypes;             /* bits 0-3 == outgoing edge bitmap;
909                                         * bit 4 set iff corner clue.
910                                         * Hence, 0 means non-vertex;
911                                         * nonzero but bit 4 zero = straight. */
912         int *neighbour[2];          /* indices of neighbour vertices in loop */
913         tdq *vertextypes_todo;
914
915         char *blackclues;              /* is each vertex a black clue site? */
916         tdq *blackclues_todo;
917     } boundaries[2];                   /* boundaries[0]=WHITE, [1]=BLACK */
918
919     char *faces;          /* remember last-seen colour of each face */
920     tdq *faces_todo;
921
922     int score;
923
924     grid *g;
925 };
926 int pearl_loopgen_bias(void *vctx, char *board, int face)
927 {
928     struct pearl_loopgen_bias_ctx *ctx = (struct pearl_loopgen_bias_ctx *)vctx;
929     grid *g = ctx->g;
930     int oldface, newface;
931     int i, j, k;
932
933     tdq_add(ctx->faces_todo, face);
934     while ((j = tdq_remove(ctx->faces_todo)) >= 0) {
935         oldface = ctx->faces[j];
936         ctx->faces[j] = newface = board[j];
937         for (i = 0; i < 2; i++) {
938             struct pearl_loopgen_bias_ctx_boundary *b = &ctx->boundaries[i];
939             int c = b->colour;
940
941             /*
942              * If the face has changed either from or to colour c, we need
943              * to reprocess the edges for this boundary.
944              */
945             if (oldface == c || newface == c) {
946                 grid_face *f = &g->faces[face];
947                 for (k = 0; k < f->order; k++)
948                     tdq_add(b->edges_todo, f->edges[k] - g->edges);
949             }
950         }
951     }
952
953     for (i = 0; i < 2; i++) {
954         struct pearl_loopgen_bias_ctx_boundary *b = &ctx->boundaries[i];
955         int c = b->colour;
956
957         /*
958          * Go through the to-do list of edges. For each edge, decide
959          * anew whether it's part of this boundary or not. Any edge
960          * that changes state has to have both its endpoints put on
961          * the vertextypes_todo list.
962          */
963         while ((j = tdq_remove(b->edges_todo)) >= 0) {
964             grid_edge *e = &g->edges[j];
965             int fc1 = e->face1 ? board[e->face1 - g->faces] : FACE_BLACK;
966             int fc2 = e->face2 ? board[e->face2 - g->faces] : FACE_BLACK;
967             int oldedge = b->edges[j];
968             int newedge = (fc1==c) ^ (fc2==c);
969             if (oldedge != newedge) {
970                 b->edges[j] = newedge;
971                 tdq_add(b->vertextypes_todo, e->dot1 - g->dots);
972                 tdq_add(b->vertextypes_todo, e->dot2 - g->dots);
973             }
974         }
975
976         /*
977          * Go through the to-do list of vertices whose types need
978          * refreshing. For each one, decide whether it's a corner, a
979          * straight, or a vertex not in the loop, and in the former
980          * two cases also work out the indices of its neighbour
981          * vertices along the loop. Any vertex that changes state must
982          * be put back on the to-do list for deciding if it's a black
983          * clue site, and so must its two new neighbours _and_ its two
984          * old neighbours.
985          */
986         while ((j = tdq_remove(b->vertextypes_todo)) >= 0) {
987             grid_dot *d = &g->dots[j];
988             int neighbours[2], type = 0, n = 0;
989             
990             for (k = 0; k < d->order; k++) {
991                 grid_edge *e = d->edges[k];
992                 grid_dot *d2 = (e->dot1 == d ? e->dot2 : e->dot1);
993                 /* dir == 0,1,2,3 for an edge going L,U,R,D */
994                 int dir = (d->y == d2->y) + 2*(d->x+d->y > d2->x+d2->y);
995                 int ei = e - g->edges;
996                 if (b->edges[ei]) {
997                     type |= 1 << dir;
998                     neighbours[n] = d2 - g->dots; 
999                     n++;
1000                 }
1001             }
1002
1003             /*
1004              * Decide if it's a corner, and set the corner flag if so.
1005              */
1006             if (type != 0 && type != 0x5 && type != 0xA)
1007                 type |= 0x10;
1008
1009             if (type != b->vertextypes[j]) {
1010                 /*
1011                  * Recompute old neighbours, if any.
1012                  */
1013                 if (b->vertextypes[j]) {
1014                     tdq_add(b->blackclues_todo, b->neighbour[0][j]);
1015                     tdq_add(b->blackclues_todo, b->neighbour[1][j]);
1016                 }
1017                 /*
1018                  * Recompute this vertex.
1019                  */
1020                 tdq_add(b->blackclues_todo, j);
1021                 b->vertextypes[j] = type;
1022                 /*
1023                  * Recompute new neighbours, if any.
1024                  */
1025                 if (b->vertextypes[j]) {
1026                     b->neighbour[0][j] = neighbours[0];
1027                     b->neighbour[1][j] = neighbours[1];
1028                     tdq_add(b->blackclues_todo, b->neighbour[0][j]);
1029                     tdq_add(b->blackclues_todo, b->neighbour[1][j]);
1030                 }
1031             }
1032         }
1033
1034         /*
1035          * Go through the list of vertices which we must check to see
1036          * if they're black clue sites. Each one is a black clue site
1037          * iff it is a corner and its loop neighbours are non-corners.
1038          * Adjust the running total of black clues we've counted.
1039          */
1040         while ((j = tdq_remove(b->blackclues_todo)) >= 0) {
1041             ctx->score -= b->blackclues[j];
1042             b->blackclues[j] = ((b->vertextypes[j] & 0x10) &&
1043                                 !((b->vertextypes[b->neighbour[0][j]] |
1044                                    b->vertextypes[b->neighbour[1][j]])
1045                                   & 0x10));
1046             ctx->score += b->blackclues[j];
1047         }
1048     }
1049
1050     return ctx->score;
1051 }
1052
1053 void pearl_loopgen(int w, int h, char *lines, random_state *rs)
1054 {
1055     grid *g = grid_new(GRID_SQUARE, w-1, h-1, NULL);
1056     char *board = snewn(g->num_faces, char);
1057     int i, s = g->tilesize;
1058     struct pearl_loopgen_bias_ctx biasctx;
1059
1060     memset(lines, 0, w*h);
1061
1062     /*
1063      * Initialise the context for the bias function. Initially we fill
1064      * all the to-do lists, so that the first call will scan
1065      * everything; thereafter the lists stay empty so we make
1066      * incremental changes.
1067      */
1068     biasctx.g = g;
1069     biasctx.faces = snewn(g->num_faces, char);
1070     biasctx.faces_todo = tdq_new(g->num_faces);
1071     tdq_fill(biasctx.faces_todo);
1072     biasctx.score = 0;
1073     memset(biasctx.faces, FACE_GREY, g->num_faces);
1074     for (i = 0; i < 2; i++) {
1075         biasctx.boundaries[i].edges = snewn(g->num_edges, char);
1076         memset(biasctx.boundaries[i].edges, 0, g->num_edges);
1077         biasctx.boundaries[i].edges_todo = tdq_new(g->num_edges);
1078         tdq_fill(biasctx.boundaries[i].edges_todo);
1079         biasctx.boundaries[i].vertextypes = snewn(g->num_dots, char);
1080         memset(biasctx.boundaries[i].vertextypes, 0, g->num_dots);
1081         biasctx.boundaries[i].neighbour[0] = snewn(g->num_dots, int);
1082         biasctx.boundaries[i].neighbour[1] = snewn(g->num_dots, int);
1083         biasctx.boundaries[i].vertextypes_todo = tdq_new(g->num_dots);
1084         tdq_fill(biasctx.boundaries[i].vertextypes_todo);
1085         biasctx.boundaries[i].blackclues = snewn(g->num_dots, char);
1086         memset(biasctx.boundaries[i].blackclues, 0, g->num_dots);
1087         biasctx.boundaries[i].blackclues_todo = tdq_new(g->num_dots);
1088         tdq_fill(biasctx.boundaries[i].blackclues_todo);
1089     }
1090     biasctx.boundaries[0].colour = FACE_WHITE;
1091     biasctx.boundaries[1].colour = FACE_BLACK;
1092     generate_loop(g, board, rs, pearl_loopgen_bias, &biasctx);
1093     sfree(biasctx.faces);
1094     tdq_free(biasctx.faces_todo);
1095     for (i = 0; i < 2; i++) {
1096         sfree(biasctx.boundaries[i].edges);
1097         tdq_free(biasctx.boundaries[i].edges_todo);
1098         sfree(biasctx.boundaries[i].vertextypes);
1099         sfree(biasctx.boundaries[i].neighbour[0]);
1100         sfree(biasctx.boundaries[i].neighbour[1]);
1101         tdq_free(biasctx.boundaries[i].vertextypes_todo);
1102         sfree(biasctx.boundaries[i].blackclues);
1103         tdq_free(biasctx.boundaries[i].blackclues_todo);
1104     }
1105
1106     for (i = 0; i < g->num_edges; i++) {
1107         grid_edge *e = g->edges + i;
1108         enum face_colour c1 = FACE_COLOUR(e->face1);
1109         enum face_colour c2 = FACE_COLOUR(e->face2);
1110         assert(c1 != FACE_GREY);
1111         assert(c2 != FACE_GREY);
1112         if (c1 != c2) {
1113             /* This grid edge is on the loop: lay line along it */
1114             int x1 = e->dot1->x/s, y1 = e->dot1->y/s;
1115             int x2 = e->dot2->x/s, y2 = e->dot2->y/s;
1116
1117             /* (x1,y1) and (x2,y2) are now in our grid coords (0-w,0-h). */
1118             if (x1 == x2) {
1119                 if (y1 > y2) SWAP(y1,y2);
1120
1121                 assert(y1+1 == y2);
1122                 lines[y1*w+x1] |= D;
1123                 lines[y2*w+x1] |= U;
1124             } else if (y1 == y2) {
1125                 if (x1 > x2) SWAP(x1,x2);
1126
1127                 assert(x1+1 == x2);
1128                 lines[y1*w+x1] |= R;
1129                 lines[y1*w+x2] |= L;
1130             } else
1131                 assert(!"grid with diagonal coords?!");
1132         }
1133     }
1134
1135     grid_free(g);
1136     sfree(board);
1137
1138 #if defined LOOPGEN_DIAGNOSTICS && !defined GENERATION_DIAGNOSTICS
1139     printf("as returned:\n");
1140     for (y = 0; y < h; y++) {
1141         for (x = 0; x < w; x++) {
1142             int type = lines[y*w+x];
1143             char s[5], *p = s;
1144             if (type & L) *p++ = 'L';
1145             if (type & R) *p++ = 'R';
1146             if (type & U) *p++ = 'U';
1147             if (type & D) *p++ = 'D';
1148             *p = '\0';
1149             printf("%3s", s);
1150         }
1151         printf("\n");
1152     }
1153     printf("\n");
1154 #endif
1155 }
1156
1157 static int new_clues(const game_params *params, random_state *rs,
1158                      char *clues, char *grid)
1159 {
1160     int w = params->w, h = params->h, diff = params->difficulty;
1161     int ngen = 0, x, y, d, ret, i;
1162
1163
1164     /*
1165      * Difficulty exception: 5x5 Tricky is not generable (the
1166      * generator will spin forever trying) and so we fudge it to Easy.
1167      */
1168     if (w == 5 && h == 5 && diff > DIFF_EASY)
1169         diff = DIFF_EASY;
1170
1171     while (1) {
1172         ngen++;
1173         pearl_loopgen(w, h, grid, rs);
1174
1175 #ifdef GENERATION_DIAGNOSTICS
1176         printf("grid array:\n");
1177         for (y = 0; y < h; y++) {
1178             for (x = 0; x < w; x++) {
1179                 int type = grid[y*w+x];
1180                 char s[5], *p = s;
1181                 if (type & L) *p++ = 'L';
1182                 if (type & R) *p++ = 'R';
1183                 if (type & U) *p++ = 'U';
1184                 if (type & D) *p++ = 'D';
1185                 *p = '\0';
1186                 printf("%2s ", s);
1187             }
1188             printf("\n");
1189         }
1190         printf("\n");
1191 #endif
1192
1193         /*
1194          * Set up the maximal clue array.
1195          */
1196         for (y = 0; y < h; y++)
1197             for (x = 0; x < w; x++) {
1198                 int type = grid[y*w+x];
1199
1200                 clues[y*w+x] = NOCLUE;
1201
1202                 if ((bLR|bUD) & (1 << type)) {
1203                     /*
1204                      * This is a straight; see if it's a viable
1205                      * candidate for a straight clue. It qualifies if
1206                      * at least one of the squares it connects to is a
1207                      * corner.
1208                      */
1209                     for (d = 1; d <= 8; d += d) if (type & d) {
1210                         int xx = x + DX(d), yy = y + DY(d);
1211                         assert(xx >= 0 && xx < w && yy >= 0 && yy < h);
1212                         if ((bLU|bLD|bRU|bRD) & (1 << grid[yy*w+xx]))
1213                             break;
1214                     }
1215                     if (d <= 8)        /* we found one */
1216                         clues[y*w+x] = STRAIGHT;
1217                 } else if ((bLU|bLD|bRU|bRD) & (1 << type)) {
1218                     /*
1219                      * This is a corner; see if it's a viable candidate
1220                      * for a corner clue. It qualifies if all the
1221                      * squares it connects to are straights.
1222                      */
1223                     for (d = 1; d <= 8; d += d) if (type & d) {
1224                         int xx = x + DX(d), yy = y + DY(d);
1225                         assert(xx >= 0 && xx < w && yy >= 0 && yy < h);
1226                         if (!((bLR|bUD) & (1 << grid[yy*w+xx])))
1227                             break;
1228                     }
1229                     if (d > 8)         /* we didn't find a counterexample */
1230                         clues[y*w+x] = CORNER;
1231                 }
1232             }
1233
1234 #ifdef GENERATION_DIAGNOSTICS
1235         printf("clue array:\n");
1236         for (y = 0; y < h; y++) {
1237             for (x = 0; x < w; x++) {
1238                 printf("%c", " *O"[(unsigned char)clues[y*w+x]]);
1239             }
1240             printf("\n");
1241         }
1242         printf("\n");
1243 #endif
1244
1245         if (!params->nosolve) {
1246             int *cluespace, *straights, *corners;
1247             int nstraights, ncorners, nstraightpos, ncornerpos;
1248
1249             /*
1250              * See if we can solve the puzzle just like this.
1251              */
1252             ret = pearl_solve(w, h, clues, grid, diff, FALSE);
1253             assert(ret > 0);           /* shouldn't be inconsistent! */
1254             if (ret != 1)
1255                 continue;                      /* go round and try again */
1256
1257             /*
1258              * Check this puzzle isn't too easy.
1259              */
1260             if (diff > DIFF_EASY) {
1261                 ret = pearl_solve(w, h, clues, grid, diff-1, FALSE);
1262                 assert(ret > 0);
1263                 if (ret == 1)
1264                     continue; /* too easy: try again */
1265             }
1266
1267             /*
1268              * Now shuffle the grid points and gradually remove the
1269              * clues to find a minimal set which still leaves the
1270              * puzzle soluble.
1271              *
1272              * We preferentially attempt to remove whichever type of
1273              * clue is currently most numerous, to combat a general
1274              * tendency of plain random generation to bias in favour
1275              * of many white clues and few black.
1276              *
1277              * 'nstraights' and 'ncorners' count the number of clues
1278              * of each type currently remaining in the grid;
1279              * 'nstraightpos' and 'ncornerpos' count the clues of each
1280              * type we have left to try to remove. (Clues which we
1281              * have tried and failed to remove are counted by the
1282              * former but not the latter.)
1283              */
1284             cluespace = snewn(w*h, int);
1285             straights = cluespace;
1286             nstraightpos = 0;
1287             for (i = 0; i < w*h; i++)
1288                 if (clues[i] == STRAIGHT)
1289                     straights[nstraightpos++] = i;
1290             corners = straights + nstraightpos;
1291             ncornerpos = 0;
1292             for (i = 0; i < w*h; i++)
1293                 if (clues[i] == STRAIGHT)
1294                     corners[ncornerpos++] = i;
1295             nstraights = nstraightpos;
1296             ncorners = ncornerpos;
1297
1298             shuffle(straights, nstraightpos, sizeof(*straights), rs);
1299             shuffle(corners, ncornerpos, sizeof(*corners), rs);
1300             while (nstraightpos > 0 || ncornerpos > 0) {
1301                 int cluepos;
1302                 int clue;
1303
1304                 /*
1305                  * Decide which clue to try to remove next. If both
1306                  * types are available, we choose whichever kind is
1307                  * currently overrepresented; otherwise we take
1308                  * whatever we can get.
1309                  */
1310                 if (nstraightpos > 0 && ncornerpos > 0) {
1311                     if (nstraights >= ncorners)
1312                         cluepos = straights[--nstraightpos];
1313                     else
1314                         cluepos = straights[--ncornerpos];
1315                 } else {
1316                     if (nstraightpos > 0)
1317                         cluepos = straights[--nstraightpos];
1318                     else
1319                         cluepos = straights[--ncornerpos];
1320                 }
1321
1322                 y = cluepos / w;
1323                 x = cluepos % w;
1324
1325                 clue = clues[y*w+x];
1326                 clues[y*w+x] = 0;              /* try removing this clue */
1327
1328                 ret = pearl_solve(w, h, clues, grid, diff, FALSE);
1329                 assert(ret > 0);
1330                 if (ret != 1)
1331                     clues[y*w+x] = clue;   /* oops, put it back again */
1332             }
1333             sfree(cluespace);
1334         }
1335
1336 #ifdef FINISHED_PUZZLE
1337         printf("clue array:\n");
1338         for (y = 0; y < h; y++) {
1339             for (x = 0; x < w; x++) {
1340                 printf("%c", " *O"[(unsigned char)clues[y*w+x]]);
1341             }
1342             printf("\n");
1343         }
1344         printf("\n");
1345 #endif
1346
1347         break;                         /* got it */
1348     }
1349
1350     debug(("%d %dx%d loops before finished puzzle.\n", ngen, w, h));
1351
1352     return ngen;
1353 }
1354
1355 static char *new_game_desc(const game_params *params, random_state *rs,
1356                            char **aux, int interactive)
1357 {
1358     char *grid, *clues;
1359     char *desc;
1360     int w = params->w, h = params->h, i, j;
1361
1362     grid = snewn(w*h, char);
1363     clues = snewn(w*h, char);
1364
1365     new_clues(params, rs, clues, grid);
1366
1367     desc = snewn(w * h + 1, char);
1368     for (i = j = 0; i < w*h; i++) {
1369         if (clues[i] == NOCLUE && j > 0 &&
1370             desc[j-1] >= 'a' && desc[j-1] < 'z')
1371             desc[j-1]++;
1372         else if (clues[i] == NOCLUE)
1373             desc[j++] = 'a';
1374         else if (clues[i] == CORNER)
1375             desc[j++] = 'B';
1376         else if (clues[i] == STRAIGHT)
1377             desc[j++] = 'W';
1378     }
1379     desc[j] = '\0';
1380
1381     *aux = snewn(w*h+1, char);
1382     for (i = 0; i < w*h; i++)
1383         (*aux)[i] = (grid[i] < 10) ? (grid[i] + '0') : (grid[i] + 'A' - 10);
1384     (*aux)[w*h] = '\0';
1385
1386     sfree(grid);
1387     sfree(clues);
1388
1389     return desc;
1390 }
1391
1392 static const char *validate_desc(const game_params *params, const char *desc)
1393 {
1394     int i, sizesofar;
1395     const int totalsize = params->w * params->h;
1396
1397     sizesofar = 0;
1398     for (i = 0; desc[i]; i++) {
1399         if (desc[i] >= 'a' && desc[i] <= 'z')
1400             sizesofar += desc[i] - 'a' + 1;
1401         else if (desc[i] == 'B' || desc[i] == 'W')
1402             sizesofar++;
1403         else
1404             return "unrecognised character in string";
1405     }
1406
1407     if (sizesofar > totalsize)
1408         return "string too long";
1409     else if (sizesofar < totalsize)
1410         return "string too short";
1411
1412     return NULL;
1413 }
1414
1415 static game_state *new_game(midend *me, const game_params *params,
1416                             const char *desc)
1417 {
1418     game_state *state = snew(game_state);
1419     int i, j, sz = params->w*params->h;
1420
1421     state->completed = state->used_solve = FALSE;
1422     state->shared = snew(struct shared_state);
1423
1424     state->shared->w = params->w;
1425     state->shared->h = params->h;
1426     state->shared->sz = sz;
1427     state->shared->refcnt = 1;
1428     state->shared->clues = snewn(sz, char);
1429     for (i = j = 0; desc[i]; i++) {
1430         assert(j < sz);
1431         if (desc[i] >= 'a' && desc[i] <= 'z') {
1432             int n = desc[i] - 'a' + 1;
1433             assert(j + n <= sz);
1434             while (n-- > 0)
1435                 state->shared->clues[j++] = NOCLUE;
1436         } else if (desc[i] == 'B') {
1437             state->shared->clues[j++] = CORNER;
1438         } else if (desc[i] == 'W') {
1439             state->shared->clues[j++] = STRAIGHT;
1440         }
1441     }
1442
1443     state->lines = snewn(sz, char);
1444     state->errors = snewn(sz, char);
1445     state->marks = snewn(sz, char);
1446     for (i = 0; i < sz; i++)
1447         state->lines[i] = state->errors[i] = state->marks[i] = BLANK;
1448
1449     return state;
1450 }
1451
1452 static game_state *dup_game(const game_state *state)
1453 {
1454     game_state *ret = snew(game_state);
1455     int sz = state->shared->sz, i;
1456
1457     ret->shared = state->shared;
1458     ret->completed = state->completed;
1459     ret->used_solve = state->used_solve;
1460     ++ret->shared->refcnt;
1461
1462     ret->lines = snewn(sz, char);
1463     ret->errors = snewn(sz, char);
1464     ret->marks = snewn(sz, char);
1465     for (i = 0; i < sz; i++) {
1466         ret->lines[i] = state->lines[i];
1467         ret->errors[i] = state->errors[i];
1468         ret->marks[i] = state->marks[i];
1469     }
1470
1471     return ret;
1472 }
1473
1474 static void free_game(game_state *state)
1475 {
1476     assert(state);
1477     if (--state->shared->refcnt == 0) {
1478         sfree(state->shared->clues);
1479         sfree(state->shared);
1480     }
1481     sfree(state->lines);
1482     sfree(state->errors);
1483     sfree(state->marks);
1484     sfree(state);
1485 }
1486
1487 static char nbits[16] = { 0, 1, 1, 2,
1488                           1, 2, 2, 3,
1489                           1, 2, 2, 3,
1490                           2, 3, 3, 4 };
1491 #define NBITS(l) ( ((l) < 0 || (l) > 15) ? 4 : nbits[l] )
1492
1493 #define ERROR_CLUE 16
1494
1495 static void dsf_update_completion(game_state *state, int ax, int ay, char dir,
1496                                  int *dsf)
1497 {
1498     int w = state->shared->w /*, h = state->shared->h */;
1499     int ac = ay*w+ax, bx, by, bc;
1500
1501     if (!(state->lines[ac] & dir)) return; /* no link */
1502     bx = ax + DX(dir); by = ay + DY(dir);
1503
1504     assert(INGRID(state, bx, by)); /* should not have a link off grid */
1505
1506     bc = by*w+bx;
1507     assert(state->lines[bc] & F(dir)); /* should have reciprocal link */
1508     if (!(state->lines[bc] & F(dir))) return;
1509
1510     dsf_merge(dsf, ac, bc);
1511 }
1512
1513 static void check_completion(game_state *state, int mark)
1514 {
1515     int w = state->shared->w, h = state->shared->h, x, y, i, d;
1516     int had_error = FALSE;
1517     int *dsf, *component_state;
1518     int nsilly, nloop, npath, largest_comp, largest_size, total_pathsize;
1519     enum { COMP_NONE, COMP_LOOP, COMP_PATH, COMP_SILLY, COMP_EMPTY };
1520
1521     if (mark) {
1522         for (i = 0; i < w*h; i++) {
1523             state->errors[i] = 0;
1524         }
1525     }
1526
1527 #define ERROR(x,y,e) do { had_error = TRUE; if (mark) state->errors[(y)*w+(x)] |= (e); } while(0)
1528
1529     /*
1530      * Analyse the solution into loops, paths and stranger things.
1531      * Basic strategy here is all the same as in Loopy - see the big
1532      * comment in loopy.c's check_completion() - and for exactly the
1533      * same reasons, since Loopy and Pearl have basically the same
1534      * form of expected solution.
1535      */
1536     dsf = snew_dsf(w*h);
1537
1538     /* Build the dsf. */
1539     for (x = 0; x < w; x++) {
1540         for (y = 0; y < h; y++) {
1541             dsf_update_completion(state, x, y, R, dsf);
1542             dsf_update_completion(state, x, y, D, dsf);
1543         }
1544     }
1545
1546     /* Initialise a state variable for each connected component. */
1547     component_state = snewn(w*h, int);
1548     for (i = 0; i < w*h; i++) {
1549         if (dsf_canonify(dsf, i) == i)
1550             component_state[i] = COMP_LOOP;
1551         else
1552             component_state[i] = COMP_NONE;
1553     }
1554
1555     /*
1556      * Classify components, and mark errors where a square has more
1557      * than two line segments.
1558      */
1559     for (x = 0; x < w; x++) {
1560         for (y = 0; y < h; y++) {
1561             int type = state->lines[y*w+x];
1562             int degree = NBITS(type);
1563             int comp = dsf_canonify(dsf, y*w+x);
1564             if (degree > 2) {
1565                 ERROR(x,y,type);
1566                 component_state[comp] = COMP_SILLY;
1567             } else if (degree == 0) {
1568                 component_state[comp] = COMP_EMPTY;
1569             } else if (degree == 1) {
1570                 if (component_state[comp] != COMP_SILLY)
1571                     component_state[comp] = COMP_PATH;
1572             }
1573         }
1574     }
1575
1576     /* Count the components, and find the largest sensible one. */
1577     nsilly = nloop = npath = 0;
1578     total_pathsize = 0;
1579     largest_comp = largest_size = -1;
1580     for (i = 0; i < w*h; i++) {
1581         if (component_state[i] == COMP_SILLY) {
1582             nsilly++;
1583         } else if (component_state[i] == COMP_PATH) {
1584             total_pathsize += dsf_size(dsf, i);
1585             npath = 1;
1586         } else if (component_state[i] == COMP_LOOP) {
1587             int this_size;
1588
1589             nloop++;
1590
1591             if ((this_size = dsf_size(dsf, i)) > largest_size) {
1592                 largest_comp = i;
1593                 largest_size = this_size;
1594             }
1595         }
1596     }
1597     if (largest_size < total_pathsize) {
1598         largest_comp = -1;             /* means the paths */
1599         largest_size = total_pathsize;
1600     }
1601
1602     if (nloop > 0 && nloop + npath > 1) {
1603         /*
1604          * If there are at least two sensible components including at
1605          * least one loop, highlight every sensible component that is
1606          * not the largest one.
1607          */
1608         for (i = 0; i < w*h; i++) {
1609             int comp = dsf_canonify(dsf, i);
1610             if ((component_state[comp] == COMP_PATH &&
1611                  -1 != largest_comp) ||
1612                 (component_state[comp] == COMP_LOOP &&
1613                  comp != largest_comp))
1614                 ERROR(i%w, i/w, state->lines[i]);
1615         }
1616     }
1617
1618     /* Now we've finished with the dsf and component states. The only
1619      * thing we'll need to remember later on is whether all edges were
1620      * part of a single loop, for which our counter variables
1621      * nsilly,nloop,npath are enough. */
1622     sfree(component_state);
1623     sfree(dsf);
1624
1625     /*
1626      * Check that no clues are contradicted. This code is similar to
1627      * the code that sets up the maximal clue array for any given
1628      * loop.
1629      */
1630     for (x = 0; x < w; x++) {
1631         for (y = 0; y < h; y++) {
1632             int type = state->lines[y*w+x];
1633             if (state->shared->clues[y*w+x] == CORNER) {
1634                 /* Supposed to be a corner: will find a contradiction if
1635                  * it actually contains a straight line, or if it touches any
1636                  * corners. */
1637                 if ((bLR|bUD) & (1 << type)) {
1638                     ERROR(x,y,ERROR_CLUE); /* actually straight */
1639                 }
1640                 for (d = 1; d <= 8; d += d) if (type & d) {
1641                     int xx = x + DX(d), yy = y + DY(d);
1642                     if (!INGRID(state, xx, yy)) {
1643                         ERROR(x,y,d); /* leads off grid */
1644                     } else {
1645                         if ((bLU|bLD|bRU|bRD) & (1 << state->lines[yy*w+xx])) {
1646                             ERROR(x,y,ERROR_CLUE); /* touches corner */
1647                         }
1648                     }
1649                 }
1650             } else if (state->shared->clues[y*w+x] == STRAIGHT) {
1651                 /* Supposed to be straight: will find a contradiction if
1652                  * it actually contains a corner, or if it only touches
1653                  * straight lines. */
1654                 if ((bLU|bLD|bRU|bRD) & (1 << type)) {
1655                     ERROR(x,y,ERROR_CLUE); /* actually a corner */
1656                 }
1657                 i = 0;
1658                 for (d = 1; d <= 8; d += d) if (type & d) {
1659                     int xx = x + DX(d), yy = y + DY(d);
1660                     if (!INGRID(state, xx, yy)) {
1661                         ERROR(x,y,d); /* leads off grid */
1662                     } else {
1663                         if ((bLR|bUD) & (1 << state->lines[yy*w+xx]))
1664                             i++; /* a straight */
1665                     }
1666                 }
1667                 if (i >= 2 && NBITS(type) >= 2) {
1668                     ERROR(x,y,ERROR_CLUE); /* everything touched is straight */
1669                 }
1670             }
1671         }
1672     }
1673
1674     if (nloop == 1 && nsilly == 0 && npath == 0) {
1675         /*
1676          * If there's exactly one loop (so that the puzzle is at least
1677          * potentially complete), we need to ensure it hasn't left any
1678          * clue out completely.
1679          */
1680         for (x = 0; x < w; x++) {
1681             for (y = 0; y < h; y++) {
1682                 if (state->lines[y*w+x] == BLANK) {
1683                     if (state->shared->clues[y*w+x] != NOCLUE) {
1684                         /* the loop doesn't include this clue square! */
1685                         ERROR(x, y, ERROR_CLUE);
1686                     }
1687                 }
1688             }
1689         }
1690
1691         /*
1692          * But if not, then we're done!
1693          */
1694         if (!had_error)
1695             state->completed = TRUE;
1696     }
1697 }
1698
1699 /* completion check:
1700  *
1701  * - no clues must be contradicted (highlight clue itself in error if so)
1702  * - if there is a closed loop it must include every line segment laid
1703  *    - if there's a smaller closed loop then highlight whole loop as error
1704  * - no square must have more than 2 lines radiating from centre point
1705  *   (highlight all lines in that square as error if so)
1706  */
1707
1708 static char *solve_for_diff(game_state *state, char *old_lines, char *new_lines)
1709 {
1710     int w = state->shared->w, h = state->shared->h, i;
1711     char *move = snewn(w*h*40, char), *p = move;
1712
1713     *p++ = 'S';
1714     for (i = 0; i < w*h; i++) {
1715         if (old_lines[i] != new_lines[i]) {
1716             p += sprintf(p, ";R%d,%d,%d", new_lines[i], i%w, i/w);
1717         }
1718     }
1719     *p++ = '\0';
1720     move = sresize(move, p - move, char);
1721
1722     return move;
1723 }
1724
1725 static char *solve_game(const game_state *state, const game_state *currstate,
1726                         const char *aux, const char **error)
1727 {
1728     game_state *solved = dup_game(state);
1729     int i, ret, sz = state->shared->sz;
1730     char *move;
1731
1732     if (aux) {
1733         for (i = 0; i < sz; i++) {
1734             if (aux[i] >= '0' && aux[i] <= '9')
1735                 solved->lines[i] = aux[i] - '0';
1736             else if (aux[i] >= 'A' && aux[i] <= 'F')
1737                 solved->lines[i] = aux[i] - 'A' + 10;
1738             else {
1739                 *error = "invalid char in aux";
1740                 move = NULL;
1741                 goto done;
1742             }
1743         }
1744         ret = 1;
1745     } else {
1746         /* Try to solve with present (half-solved) state first: if there's no
1747          * solution from there go back to original state. */
1748         ret = pearl_solve(currstate->shared->w, currstate->shared->h,
1749                           currstate->shared->clues, solved->lines,
1750                           DIFFCOUNT, FALSE);
1751         if (ret < 1)
1752             ret = pearl_solve(state->shared->w, state->shared->h,
1753                               state->shared->clues, solved->lines,
1754                               DIFFCOUNT, FALSE);
1755
1756     }
1757
1758     if (ret < 1) {
1759         *error = "Unable to find solution";
1760         move = NULL;
1761     } else {
1762         move = solve_for_diff(solved, currstate->lines, solved->lines);
1763     }
1764
1765 done:
1766     free_game(solved);
1767     return move;
1768 }
1769
1770 static int game_can_format_as_text_now(const game_params *params)
1771 {
1772     return TRUE;
1773 }
1774
1775 static char *game_text_format(const game_state *state)
1776 {
1777     int w = state->shared->w, h = state->shared->h, cw = 4, ch = 2;
1778     int gw = cw*(w-1) + 2, gh = ch*(h-1) + 1, len = gw * gh, r, c, j;
1779     char *board = snewn(len + 1, char);
1780
1781     assert(board);
1782     memset(board, ' ', len);
1783
1784     for (r = 0; r < h; ++r) {
1785         for (c = 0; c < w; ++c) {
1786             int i = r*w + c, cell = r*ch*gw + c*cw;
1787             board[cell] = "+BW"[(unsigned char)state->shared->clues[i]];
1788             if (c < w - 1 && (state->lines[i] & R || state->lines[i+1] & L))
1789                 memset(board + cell + 1, '-', cw - 1);
1790             if (r < h - 1 && (state->lines[i] & D || state->lines[i+w] & U))
1791                 for (j = 1; j < ch; ++j) board[cell + j*gw] = '|';
1792             if (c < w - 1 && (state->marks[i] & R || state->marks[i+1] & L))
1793                 board[cell + cw/2] = 'x';
1794             if (r < h - 1 && (state->marks[i] & D || state->marks[i+w] & U))
1795                 board[cell + (ch/2 * gw)] = 'x';
1796         }
1797
1798         for (j = 0; j < (r == h - 1 ? 1 : ch); ++j)
1799             board[r*ch*gw + (gw - 1) + j*gw] = '\n';
1800     }
1801
1802     board[len] = '\0';
1803     return board;
1804 }
1805
1806 struct game_ui {
1807     int *dragcoords;       /* list of (y*w+x) coords in drag so far */
1808     int ndragcoords;       /* number of entries in dragcoords.
1809                             * 0 = click but no drag yet. -1 = no drag at all */
1810     int clickx, clicky;    /* pixel position of initial click */
1811
1812     int curx, cury;        /* grid position of keyboard cursor */
1813     int cursor_active;     /* TRUE iff cursor is shown */
1814 };
1815
1816 static game_ui *new_ui(const game_state *state)
1817 {
1818     game_ui *ui = snew(game_ui);
1819     int sz = state->shared->sz;
1820
1821     ui->ndragcoords = -1;
1822     ui->dragcoords = snewn(sz, int);
1823     ui->cursor_active = FALSE;
1824     ui->curx = ui->cury = 0;
1825
1826     return ui;
1827 }
1828
1829 static void free_ui(game_ui *ui)
1830 {
1831     sfree(ui->dragcoords);
1832     sfree(ui);
1833 }
1834
1835 static char *encode_ui(const game_ui *ui)
1836 {
1837     return NULL;
1838 }
1839
1840 static void decode_ui(game_ui *ui, const char *encoding)
1841 {
1842 }
1843
1844 static void game_changed_state(game_ui *ui, const game_state *oldstate,
1845                                const game_state *newstate)
1846 {
1847 }
1848
1849 #define PREFERRED_TILE_SIZE 31
1850 #define HALFSZ (ds->halfsz)
1851 #define TILE_SIZE (ds->halfsz*2 + 1)
1852
1853 #define BORDER ((get_gui_style() == GUI_LOOPY) ? (TILE_SIZE/8) : (TILE_SIZE/2))
1854
1855 #define BORDER_WIDTH (max(TILE_SIZE / 32, 1))
1856
1857 #define COORD(x) ( (x) * TILE_SIZE + BORDER )
1858 #define CENTERED_COORD(x) ( COORD(x) + TILE_SIZE/2 )
1859 #define FROMCOORD(x) ( ((x) < BORDER) ? -1 : ( ((x) - BORDER) / TILE_SIZE) )
1860
1861 #define DS_ESHIFT 4     /* R/U/L/D shift, for error flags */
1862 #define DS_DSHIFT 8     /* R/U/L/D shift, for drag-in-progress flags */
1863 #define DS_MSHIFT 12    /* shift for no-line mark */
1864
1865 #define DS_ERROR_CLUE (1 << 20)
1866 #define DS_FLASH (1 << 21)
1867 #define DS_CURSOR (1 << 22)
1868
1869 enum { GUI_MASYU, GUI_LOOPY };
1870
1871 static int get_gui_style(void)
1872 {
1873     static int gui_style = -1;
1874
1875     if (gui_style == -1) {
1876         char *env = getenv("PEARL_GUI_LOOPY");
1877         if (env && (env[0] == 'y' || env[0] == 'Y'))
1878             gui_style = GUI_LOOPY;
1879         else
1880             gui_style = GUI_MASYU;
1881     }
1882     return gui_style;
1883 }
1884
1885 struct game_drawstate {
1886     int halfsz;
1887     int started;
1888
1889     int w, h, sz;
1890     unsigned int *lflags;       /* size w*h */
1891
1892     char *draglines;            /* size w*h; lines flipped by current drag */
1893 };
1894
1895 static void update_ui_drag(const game_state *state, game_ui *ui,
1896                            int gx, int gy)
1897 {
1898     int /* sz = state->shared->sz, */ w = state->shared->w;
1899     int i, ox, oy, pos;
1900     int lastpos;
1901
1902     if (!INGRID(state, gx, gy))
1903         return;                        /* square is outside grid */
1904
1905     if (ui->ndragcoords < 0)
1906         return;                        /* drag not in progress anyway */
1907
1908     pos = gy * w + gx;
1909
1910     lastpos = ui->dragcoords[ui->ndragcoords > 0 ? ui->ndragcoords-1 : 0];
1911     if (pos == lastpos)
1912         return;             /* same square as last visited one */
1913
1914     /* Drag confirmed, if it wasn't already. */
1915     if (ui->ndragcoords == 0)
1916         ui->ndragcoords = 1;
1917
1918     /*
1919      * Dragging the mouse into a square that's already been visited by
1920      * the drag path so far has the effect of truncating the path back
1921      * to that square, so a player can back out part of an uncommitted
1922      * drag without having to let go of the mouse.
1923      */
1924     for (i = 0; i < ui->ndragcoords; i++)
1925         if (pos == ui->dragcoords[i]) {
1926             ui->ndragcoords = i+1;
1927             return;
1928         }
1929
1930     /*
1931      * Otherwise, dragging the mouse into a square that's a rook-move
1932      * away from the last one on the path extends the path.
1933      */
1934     oy = ui->dragcoords[ui->ndragcoords-1] / w;
1935     ox = ui->dragcoords[ui->ndragcoords-1] % w;
1936     if (ox == gx || oy == gy) {
1937         int dx = (gx < ox ? -1 : gx > ox ? +1 : 0);
1938         int dy = (gy < oy ? -1 : gy > oy ? +1 : 0);
1939         int dir = (dy>0 ? D : dy<0 ? U : dx>0 ? R : L);
1940         while (ox != gx || oy != gy) {
1941             /*
1942              * If the drag attempts to cross a 'no line here' mark,
1943              * stop there. We physically don't allow the user to drag
1944              * over those marks.
1945              */
1946             if (state->marks[oy*w+ox] & dir)
1947                 break;
1948             ox += dx;
1949             oy += dy;
1950             ui->dragcoords[ui->ndragcoords++] = oy * w + ox;
1951         }
1952     }
1953
1954     /*
1955      * Failing that, we do nothing at all: if the user has dragged
1956      * diagonally across the board, they'll just have to return the
1957      * mouse to the last known position and do whatever they meant to
1958      * do again, more slowly and clearly.
1959      */
1960 }
1961
1962 /*
1963  * Routine shared between interpret_move and game_redraw to work out
1964  * the intended effect of a drag path on the grid.
1965  *
1966  * Call it in a loop, like this:
1967  *
1968  *     int clearing = TRUE;
1969  *     for (i = 0; i < ui->ndragcoords - 1; i++) {
1970  *         int sx, sy, dx, dy, dir, oldstate, newstate;
1971  *         interpret_ui_drag(state, ui, &clearing, i, &sx, &sy, &dx, &dy,
1972  *                           &dir, &oldstate, &newstate);
1973  *
1974  *         [do whatever is needed to handle the fact that the drag
1975  *         wants the edge from sx,sy to dx,dy (heading in direction
1976  *         'dir' at the sx,sy end) to be changed from state oldstate
1977  *         to state newstate, each of which equals either 0 or dir]
1978  *     }
1979  */
1980 static void interpret_ui_drag(const game_state *state, const game_ui *ui,
1981                               int *clearing, int i, int *sx, int *sy,
1982                               int *dx, int *dy, int *dir,
1983                               int *oldstate, int *newstate)
1984 {
1985     int w = state->shared->w;
1986     int sp = ui->dragcoords[i], dp = ui->dragcoords[i+1];
1987     *sy = sp/w;
1988     *sx = sp%w;
1989     *dy = dp/w;
1990     *dx = dp%w;
1991     *dir = (*dy>*sy ? D : *dy<*sy ? U : *dx>*sx ? R : L);
1992     *oldstate = state->lines[sp] & *dir;
1993     if (*oldstate) {
1994         /*
1995          * The edge we've dragged over was previously
1996          * present. Set it to absent, unless we've already
1997          * stopped doing that.
1998          */
1999         *newstate = *clearing ? 0 : *dir;
2000     } else {
2001         /*
2002          * The edge we've dragged over was previously
2003          * absent. Set it to present, and cancel the
2004          * 'clearing' flag so that all subsequent edges in
2005          * the drag are set rather than cleared.
2006          */
2007         *newstate = *dir;
2008         *clearing = FALSE;
2009     }
2010 }
2011
2012 static char *mark_in_direction(const game_state *state, int x, int y, int dir,
2013                                int primary, char *buf)
2014 {
2015     int w = state->shared->w /*, h = state->shared->h, sz = state->shared->sz */;
2016     int x2 = x + DX(dir);
2017     int y2 = y + DY(dir);
2018     int dir2 = F(dir);
2019
2020     char ch = primary ? 'F' : 'M', *other;
2021
2022     if (!INGRID(state, x, y) || !INGRID(state, x2, y2)) return UI_UPDATE;
2023
2024     /* disallow laying a mark over a line, or vice versa. */
2025     other = primary ? state->marks : state->lines;
2026     if (other[y*w+x] & dir || other[y2*w+x2] & dir2) return UI_UPDATE;
2027     
2028     sprintf(buf, "%c%d,%d,%d;%c%d,%d,%d", ch, dir, x, y, ch, dir2, x2, y2);
2029     return dupstr(buf);
2030 }
2031
2032 #define KEY_DIRECTION(btn) (\
2033     (btn) == CURSOR_DOWN ? D : (btn) == CURSOR_UP ? U :\
2034     (btn) == CURSOR_LEFT ? L : R)
2035
2036 static char *interpret_move(const game_state *state, game_ui *ui,
2037                             const game_drawstate *ds,
2038                             int x, int y, int button)
2039 {
2040     int w = state->shared->w, h = state->shared->h /*, sz = state->shared->sz */;
2041     int gx = FROMCOORD(x), gy = FROMCOORD(y), i;
2042     int release = FALSE;
2043     char tmpbuf[80];
2044
2045     int shift = button & MOD_SHFT, control = button & MOD_CTRL;
2046     button &= ~MOD_MASK;
2047
2048     if (IS_MOUSE_DOWN(button)) {
2049         ui->cursor_active = FALSE;
2050
2051         if (!INGRID(state, gx, gy)) {
2052             ui->ndragcoords = -1;
2053             return NULL;
2054         }
2055
2056         ui->clickx = x; ui->clicky = y;
2057         ui->dragcoords[0] = gy * w + gx;
2058         ui->ndragcoords = 0;           /* will be 1 once drag is confirmed */
2059
2060         return UI_UPDATE;
2061     }
2062
2063     if (button == LEFT_DRAG && ui->ndragcoords >= 0) {
2064         update_ui_drag(state, ui, gx, gy);
2065         return UI_UPDATE;
2066     }
2067
2068     if (IS_MOUSE_RELEASE(button)) release = TRUE;
2069
2070     if (IS_CURSOR_MOVE(button)) {
2071         if (!ui->cursor_active) {
2072             ui->cursor_active = TRUE;
2073         } else if (control | shift) {
2074             char *move;
2075             if (ui->ndragcoords > 0) return NULL;
2076             ui->ndragcoords = -1;
2077             move = mark_in_direction(state, ui->curx, ui->cury,
2078                                      KEY_DIRECTION(button), control, tmpbuf);
2079             if (control && !shift && *move)
2080                 move_cursor(button, &ui->curx, &ui->cury, w, h, FALSE);
2081             return move;
2082         } else {
2083             move_cursor(button, &ui->curx, &ui->cury, w, h, FALSE);
2084             if (ui->ndragcoords >= 0)
2085                 update_ui_drag(state, ui, ui->curx, ui->cury);
2086         }
2087         return UI_UPDATE;
2088     }
2089
2090     if (IS_CURSOR_SELECT(button)) {
2091         if (!ui->cursor_active) {
2092             ui->cursor_active = TRUE;
2093             return UI_UPDATE;
2094         } else if (button == CURSOR_SELECT) {
2095             if (ui->ndragcoords == -1) {
2096                 ui->ndragcoords = 0;
2097                 ui->dragcoords[0] = ui->cury * w + ui->curx;
2098                 ui->clickx = CENTERED_COORD(ui->curx);
2099                 ui->clicky = CENTERED_COORD(ui->cury);
2100                 return UI_UPDATE;
2101             } else release = TRUE;
2102         } else if (button == CURSOR_SELECT2 && ui->ndragcoords >= 0) {
2103             ui->ndragcoords = -1;
2104             return UI_UPDATE;
2105         }
2106     }
2107
2108     if (button == 27 || button == '\b') {
2109         ui->ndragcoords = -1;
2110         return UI_UPDATE;
2111     }
2112
2113     if (release) {
2114         if (ui->ndragcoords > 0) {
2115             /* End of a drag: process the cached line data. */
2116             int buflen = 0, bufsize = 256, tmplen;
2117             char *buf = NULL;
2118             const char *sep = "";
2119             int clearing = TRUE;
2120
2121             for (i = 0; i < ui->ndragcoords - 1; i++) {
2122                 int sx, sy, dx, dy, dir, oldstate, newstate;
2123                 interpret_ui_drag(state, ui, &clearing, i, &sx, &sy, &dx, &dy,
2124                                   &dir, &oldstate, &newstate);
2125
2126                 if (oldstate != newstate) {
2127                     if (!buf) buf = snewn(bufsize, char);
2128                     tmplen = sprintf(tmpbuf, "%sF%d,%d,%d;F%d,%d,%d", sep,
2129                                      dir, sx, sy, F(dir), dx, dy);
2130                     if (buflen + tmplen >= bufsize) {
2131                         bufsize = (buflen + tmplen) * 5 / 4 + 256;
2132                         buf = sresize(buf, bufsize, char);
2133                     }
2134                     strcpy(buf + buflen, tmpbuf);
2135                     buflen += tmplen;
2136                     sep = ";";
2137                 }
2138             }
2139
2140             ui->ndragcoords = -1;
2141
2142             return buf ? buf : UI_UPDATE;
2143         } else if (ui->ndragcoords == 0) {
2144             /* Click (or tiny drag). Work out which edge we were
2145              * closest to. */
2146             int cx, cy;
2147
2148             ui->ndragcoords = -1;
2149
2150             /*
2151              * We process clicks based on the mouse-down location,
2152              * because that's more natural for a user to carefully
2153              * control than the mouse-up.
2154              */
2155             x = ui->clickx;
2156             y = ui->clicky;
2157
2158             gx = FROMCOORD(x);
2159             gy = FROMCOORD(y);
2160             cx = CENTERED_COORD(gx);
2161             cy = CENTERED_COORD(gy);
2162
2163             if (!INGRID(state, gx, gy)) return UI_UPDATE;
2164
2165             if (max(abs(x-cx),abs(y-cy)) < TILE_SIZE/4) {
2166                 /* TODO closer to centre of grid: process as a cell click not an edge click. */
2167
2168                 return UI_UPDATE;
2169             } else {
2170                 int direction;
2171                 if (abs(x-cx) < abs(y-cy)) {
2172                     /* Closest to top/bottom edge. */
2173                     direction = (y < cy) ? U : D;
2174                 } else {
2175                     /* Closest to left/right edge. */
2176                     direction = (x < cx) ? L : R;
2177                 }
2178                 return mark_in_direction(state, gx, gy, direction,
2179                                          (button == LEFT_RELEASE), tmpbuf);
2180             }
2181         }
2182     }
2183
2184     if (button == 'H' || button == 'h')
2185         return dupstr("H");
2186
2187     return NULL;
2188 }
2189
2190 static game_state *execute_move(const game_state *state, const char *move)
2191 {
2192     int w = state->shared->w, h = state->shared->h;
2193     char c;
2194     int x, y, l, n;
2195     game_state *ret = dup_game(state);
2196
2197     debug(("move: %s\n", move));
2198
2199     while (*move) {
2200         c = *move;
2201         if (c == 'S') {
2202             ret->used_solve = TRUE;
2203             move++;
2204         } else if (c == 'L' || c == 'N' || c == 'R' || c == 'F' || c == 'M') {
2205             /* 'line' or 'noline' or 'replace' or 'flip' or 'mark' */
2206             move++;
2207             if (sscanf(move, "%d,%d,%d%n", &l, &x, &y, &n) != 3)
2208                 goto badmove;
2209             if (!INGRID(state, x, y)) goto badmove;
2210             if (l < 0 || l > 15) goto badmove;
2211
2212             if (c == 'L')
2213                 ret->lines[y*w + x] |= (char)l;
2214             else if (c == 'N')
2215                 ret->lines[y*w + x] &= ~((char)l);
2216             else if (c == 'R') {
2217                 ret->lines[y*w + x] = (char)l;
2218                 ret->marks[y*w + x] &= ~((char)l); /* erase marks too */
2219             } else if (c == 'F')
2220                 ret->lines[y*w + x] ^= (char)l;
2221             else if (c == 'M')
2222                 ret->marks[y*w + x] ^= (char)l;
2223
2224             /*
2225              * If we ended up trying to lay a line _over_ a mark,
2226              * that's a failed move: interpret_move() should have
2227              * ensured we never received a move string like that in
2228              * the first place.
2229              */
2230             if ((ret->lines[y*w + x] & (char)l) &&
2231                 (ret->marks[y*w + x] & (char)l))
2232                 goto badmove;
2233
2234             move += n;
2235         } else if (strcmp(move, "H") == 0) {
2236             pearl_solve(ret->shared->w, ret->shared->h,
2237                         ret->shared->clues, ret->lines, DIFFCOUNT, TRUE);
2238             for (n = 0; n < w*h; n++)
2239                 ret->marks[n] &= ~ret->lines[n]; /* erase marks too */
2240             move++;
2241         } else {
2242             goto badmove;
2243         }
2244         if (*move == ';')
2245             move++;
2246         else if (*move)
2247             goto badmove;
2248     }
2249
2250     check_completion(ret, TRUE);
2251
2252     return ret;
2253
2254 badmove:
2255     free_game(ret);
2256     return NULL;
2257 }
2258
2259 /* ----------------------------------------------------------------------
2260  * Drawing routines.
2261  */
2262
2263 #define FLASH_TIME 0.5F
2264
2265 static void game_compute_size(const game_params *params, int tilesize,
2266                               int *x, int *y)
2267 {
2268     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
2269     struct { int halfsz; } ads, *ds = &ads;
2270     ads.halfsz = (tilesize-1)/2;
2271
2272     *x = (params->w) * TILE_SIZE + 2 * BORDER;
2273     *y = (params->h) * TILE_SIZE + 2 * BORDER;
2274 }
2275
2276 static void game_set_size(drawing *dr, game_drawstate *ds,
2277                           const game_params *params, int tilesize)
2278 {
2279     ds->halfsz = (tilesize-1)/2;
2280 }
2281
2282 static float *game_colours(frontend *fe, int *ncolours)
2283 {
2284     float *ret = snewn(3 * NCOLOURS, float);
2285     int i;
2286
2287     game_mkhighlight(fe, ret, COL_BACKGROUND, COL_HIGHLIGHT, COL_LOWLIGHT);
2288
2289     for (i = 0; i < 3; i++) {
2290         ret[COL_BLACK * 3 + i] = 0.0F;
2291         ret[COL_WHITE * 3 + i] = 1.0F;
2292         ret[COL_GRID * 3 + i] = 0.4F;
2293     }
2294
2295     ret[COL_ERROR * 3 + 0] = 1.0F;
2296     ret[COL_ERROR * 3 + 1] = 0.0F;
2297     ret[COL_ERROR * 3 + 2] = 0.0F;
2298
2299     ret[COL_DRAGON * 3 + 0] = 0.0F;
2300     ret[COL_DRAGON * 3 + 1] = 0.0F;
2301     ret[COL_DRAGON * 3 + 2] = 1.0F;
2302
2303     ret[COL_DRAGOFF * 3 + 0] = 0.8F;
2304     ret[COL_DRAGOFF * 3 + 1] = 0.8F;
2305     ret[COL_DRAGOFF * 3 + 2] = 1.0F;
2306
2307     ret[COL_FLASH * 3 + 0] = 1.0F;
2308     ret[COL_FLASH * 3 + 1] = 1.0F;
2309     ret[COL_FLASH * 3 + 2] = 1.0F;
2310
2311     *ncolours = NCOLOURS;
2312
2313     return ret;
2314 }
2315
2316 static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
2317 {
2318     struct game_drawstate *ds = snew(struct game_drawstate);
2319     int i;
2320
2321     ds->halfsz = 0;
2322     ds->started = FALSE;
2323
2324     ds->w = state->shared->w;
2325     ds->h = state->shared->h;
2326     ds->sz = state->shared->sz;
2327     ds->lflags = snewn(ds->sz, unsigned int);
2328     for (i = 0; i < ds->sz; i++)
2329         ds->lflags[i] = 0;
2330
2331     ds->draglines = snewn(ds->sz, char);
2332
2333     return ds;
2334 }
2335
2336 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
2337 {
2338     sfree(ds->draglines);
2339     sfree(ds->lflags);
2340     sfree(ds);
2341 }
2342
2343 static void draw_lines_specific(drawing *dr, game_drawstate *ds,
2344                                 int x, int y, unsigned int lflags,
2345                                 unsigned int shift, int c)
2346 {
2347     int ox = COORD(x), oy = COORD(y);
2348     int t2 = HALFSZ, t16 = HALFSZ/4;
2349     int cx = ox + t2, cy = oy + t2;
2350     int d;
2351
2352     /* Draw each of the four directions, where laid (or error, or drag, etc.) */
2353     for (d = 1; d < 16; d *= 2) {
2354         int xoff = t2 * DX(d), yoff = t2 * DY(d);
2355         int xnudge = abs(t16 * DX(C(d))), ynudge = abs(t16 * DY(C(d)));
2356
2357         if ((lflags >> shift) & d) {
2358             int lx = cx + ((xoff < 0) ? xoff : 0) - xnudge;
2359             int ly = cy + ((yoff < 0) ? yoff : 0) - ynudge;
2360
2361             if (c == COL_DRAGOFF && !(lflags & d))
2362                 continue;
2363             if (c == COL_DRAGON && (lflags & d))
2364                 continue;
2365
2366             draw_rect(dr, lx, ly,
2367                       abs(xoff)+2*xnudge+1,
2368                       abs(yoff)+2*ynudge+1, c);
2369             /* end cap */
2370             draw_rect(dr, cx - t16, cy - t16, 2*t16+1, 2*t16+1, c);
2371         }
2372     }
2373 }
2374
2375 static void draw_square(drawing *dr, game_drawstate *ds, const game_ui *ui,
2376                         int x, int y, unsigned int lflags, char clue)
2377 {
2378     int ox = COORD(x), oy = COORD(y);
2379     int t2 = HALFSZ, t16 = HALFSZ/4;
2380     int cx = ox + t2, cy = oy + t2;
2381     int d;
2382
2383     assert(dr);
2384
2385     /* Clip to the grid square. */
2386     clip(dr, ox, oy, TILE_SIZE, TILE_SIZE);
2387
2388     /* Clear the square. */
2389     draw_rect(dr, ox, oy, TILE_SIZE, TILE_SIZE,
2390               (lflags & DS_CURSOR) ?
2391               COL_CURSOR_BACKGROUND : COL_BACKGROUND);
2392               
2393
2394     if (get_gui_style() == GUI_LOOPY) {
2395         /* Draw small dot, underneath any lines. */
2396         draw_circle(dr, cx, cy, t16, COL_GRID, COL_GRID);
2397     } else {
2398         /* Draw outline of grid square */
2399         draw_line(dr, ox, oy, COORD(x+1), oy, COL_GRID);
2400         draw_line(dr, ox, oy, ox, COORD(y+1), COL_GRID);
2401     }
2402
2403     /* Draw grid: either thin gridlines, or no-line marks.
2404      * We draw these first because the thick laid lines should be on top. */
2405     for (d = 1; d < 16; d *= 2) {
2406         int xoff = t2 * DX(d), yoff = t2 * DY(d);
2407
2408         if ((x == 0 && d == L) ||
2409             (y == 0 && d == U) ||
2410             (x == ds->w-1 && d == R) ||
2411             (y == ds->h-1 && d == D))
2412             continue; /* no gridlines out to the border. */
2413
2414         if ((lflags >> DS_MSHIFT) & d) {
2415             /* either a no-line mark ... */
2416             int mx = cx + xoff, my = cy + yoff, msz = t16;
2417
2418             draw_line(dr, mx-msz, my-msz, mx+msz, my+msz, COL_BLACK);
2419             draw_line(dr, mx-msz, my+msz, mx+msz, my-msz, COL_BLACK);
2420         } else {
2421             if (get_gui_style() == GUI_LOOPY) {
2422                 /* draw grid lines connecting centre of cells */
2423                 draw_line(dr, cx, cy, cx+xoff, cy+yoff, COL_GRID);
2424             }
2425         }
2426     }
2427
2428     /* Draw each of the four directions, where laid (or error, or drag, etc.)
2429      * Order is important here, specifically for the eventual colours of the
2430      * exposed end caps. */
2431     draw_lines_specific(dr, ds, x, y, lflags, 0,
2432                         (lflags & DS_FLASH ? COL_FLASH : COL_BLACK));
2433     draw_lines_specific(dr, ds, x, y, lflags, DS_ESHIFT, COL_ERROR);
2434     draw_lines_specific(dr, ds, x, y, lflags, DS_DSHIFT, COL_DRAGOFF);
2435     draw_lines_specific(dr, ds, x, y, lflags, DS_DSHIFT, COL_DRAGON);
2436
2437     /* Draw a clue, if present */
2438     if (clue != NOCLUE) {
2439         int c = (lflags & DS_FLASH) ? COL_FLASH :
2440                 (clue == STRAIGHT) ? COL_WHITE : COL_BLACK;
2441
2442         if (lflags & DS_ERROR_CLUE) /* draw a bigger 'error' clue circle. */
2443             draw_circle(dr, cx, cy, TILE_SIZE*3/8, COL_ERROR, COL_ERROR);
2444
2445         draw_circle(dr, cx, cy, TILE_SIZE/4, c, COL_BLACK);
2446     }
2447
2448     unclip(dr);
2449     draw_update(dr, ox, oy, TILE_SIZE, TILE_SIZE);
2450 }
2451
2452 static void game_redraw(drawing *dr, game_drawstate *ds,
2453                         const game_state *oldstate, const game_state *state,
2454                         int dir, const game_ui *ui,
2455                         float animtime, float flashtime)
2456 {
2457     int w = state->shared->w, h = state->shared->h, sz = state->shared->sz;
2458     int x, y, force = 0, flashing = 0;
2459
2460     if (!ds->started) {
2461         /*
2462          * The initial contents of the window are not guaranteed and
2463          * can vary with front ends. To be on the safe side, all games
2464          * should start by drawing a big background-colour rectangle
2465          * covering the whole window.
2466          */
2467         draw_rect(dr, 0, 0, w*TILE_SIZE + 2*BORDER, h*TILE_SIZE + 2*BORDER,
2468                   COL_BACKGROUND);
2469
2470         if (get_gui_style() == GUI_MASYU) {
2471             /*
2472              * Smaller black rectangle which is the main grid.
2473              */
2474             draw_rect(dr, BORDER - BORDER_WIDTH, BORDER - BORDER_WIDTH,
2475                       w*TILE_SIZE + 2*BORDER_WIDTH + 1,
2476                       h*TILE_SIZE + 2*BORDER_WIDTH + 1,
2477                       COL_GRID);
2478         }
2479
2480         draw_update(dr, 0, 0, w*TILE_SIZE + 2*BORDER, h*TILE_SIZE + 2*BORDER);
2481
2482         ds->started = TRUE;
2483         force = 1;
2484     }
2485
2486     if (flashtime > 0 &&
2487         (flashtime <= FLASH_TIME/3 ||
2488          flashtime >= FLASH_TIME*2/3))
2489         flashing = DS_FLASH;
2490
2491     memset(ds->draglines, 0, sz);
2492     if (ui->ndragcoords > 0) {
2493         int i, clearing = TRUE;
2494         for (i = 0; i < ui->ndragcoords - 1; i++) {
2495             int sx, sy, dx, dy, dir, oldstate, newstate;
2496             interpret_ui_drag(state, ui, &clearing, i, &sx, &sy, &dx, &dy,
2497                               &dir, &oldstate, &newstate);
2498             ds->draglines[sy*w+sx] ^= (oldstate ^ newstate);
2499             ds->draglines[dy*w+dx] ^= (F(oldstate) ^ F(newstate));
2500         }
2501     }   
2502
2503     for (x = 0; x < w; x++) {
2504         for (y = 0; y < h; y++) {
2505             unsigned int f = (unsigned int)state->lines[y*w+x];
2506             unsigned int eline = (unsigned int)(state->errors[y*w+x] & (R|U|L|D));
2507
2508             f |= eline << DS_ESHIFT;
2509             f |= ((unsigned int)ds->draglines[y*w+x]) << DS_DSHIFT;
2510             f |= ((unsigned int)state->marks[y*w+x]) << DS_MSHIFT;
2511
2512             if (state->errors[y*w+x] & ERROR_CLUE)
2513                 f |= DS_ERROR_CLUE;
2514
2515             f |= flashing;
2516
2517             if (ui->cursor_active && x == ui->curx && y == ui->cury)
2518                 f |= DS_CURSOR;
2519
2520             if (f != ds->lflags[y*w+x] || force) {
2521                 ds->lflags[y*w+x] = f;
2522                 draw_square(dr, ds, ui, x, y, f, state->shared->clues[y*w+x]);
2523             }
2524         }
2525     }
2526 }
2527
2528 static float game_anim_length(const game_state *oldstate,
2529                               const game_state *newstate, int dir, game_ui *ui)
2530 {
2531     return 0.0F;
2532 }
2533
2534 static float game_flash_length(const game_state *oldstate,
2535                                const game_state *newstate, int dir, game_ui *ui)
2536 {
2537     if (!oldstate->completed && newstate->completed &&
2538         !oldstate->used_solve && !newstate->used_solve)
2539         return FLASH_TIME;
2540     else
2541         return 0.0F;
2542 }
2543
2544 static int game_status(const game_state *state)
2545 {
2546     return state->completed ? +1 : 0;
2547 }
2548
2549 static int game_timing_state(const game_state *state, game_ui *ui)
2550 {
2551     return TRUE;
2552 }
2553
2554 static void game_print_size(const game_params *params, float *x, float *y)
2555 {
2556     int pw, ph;
2557
2558     /*
2559      * I'll use 6mm squares by default.
2560      */
2561     game_compute_size(params, 600, &pw, &ph);
2562     *x = pw / 100.0F;
2563     *y = ph / 100.0F;
2564 }
2565
2566 static void game_print(drawing *dr, const game_state *state, int tilesize)
2567 {
2568     int w = state->shared->w, h = state->shared->h, x, y;
2569     int black = print_mono_colour(dr, 0);
2570     int white = print_mono_colour(dr, 1);
2571
2572     /* No GUI_LOOPY here: only use the familiar masyu style. */
2573
2574     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
2575     game_drawstate *ds = game_new_drawstate(dr, state);
2576     game_set_size(dr, ds, NULL, tilesize);
2577
2578     /* Draw grid outlines (black). */
2579     for (x = 0; x <= w; x++)
2580         draw_line(dr, COORD(x), COORD(0), COORD(x), COORD(h), black);
2581     for (y = 0; y <= h; y++)
2582         draw_line(dr, COORD(0), COORD(y), COORD(w), COORD(y), black);
2583
2584     for (x = 0; x < w; x++) {
2585         for (y = 0; y < h; y++) {
2586             int cx = COORD(x) + HALFSZ, cy = COORD(y) + HALFSZ;
2587             int clue = state->shared->clues[y*w+x];
2588
2589             draw_lines_specific(dr, ds, x, y, state->lines[y*w+x], 0, black);
2590
2591             if (clue != NOCLUE) {
2592                 int c = (clue == CORNER) ? black : white;
2593                 draw_circle(dr, cx, cy, TILE_SIZE/4, c, black);
2594             }
2595         }
2596     }
2597
2598     game_free_drawstate(dr, ds);
2599 }
2600
2601 #ifdef COMBINED
2602 #define thegame pearl
2603 #endif
2604
2605 const struct game thegame = {
2606     "Pearl", "games.pearl", "pearl",
2607     default_params,
2608     game_fetch_preset, NULL,
2609     decode_params,
2610     encode_params,
2611     free_params,
2612     dup_params,
2613     TRUE, game_configure, custom_params,
2614     validate_params,
2615     new_game_desc,
2616     validate_desc,
2617     new_game,
2618     dup_game,
2619     free_game,
2620     TRUE, solve_game,
2621     TRUE, game_can_format_as_text_now, game_text_format,
2622     new_ui,
2623     free_ui,
2624     encode_ui,
2625     decode_ui,
2626     game_changed_state,
2627     interpret_move,
2628     execute_move,
2629     PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
2630     game_colours,
2631     game_new_drawstate,
2632     game_free_drawstate,
2633     game_redraw,
2634     game_anim_length,
2635     game_flash_length,
2636     game_status,
2637     TRUE, FALSE, game_print_size, game_print,
2638     FALSE,                             /* wants_statusbar */
2639     FALSE, game_timing_state,
2640     0,                                 /* flags */
2641 };
2642
2643 #ifdef STANDALONE_SOLVER
2644
2645 #include <time.h>
2646 #include <stdarg.h>
2647
2648 const char *quis = NULL;
2649
2650 static void usage(FILE *out) {
2651     fprintf(out, "usage: %s <params>\n", quis);
2652 }
2653
2654 static void pnum(int n, int ntot, const char *desc)
2655 {
2656     printf("%2.1f%% (%d) %s", (double)n*100.0 / (double)ntot, n, desc);
2657 }
2658
2659 static void start_soak(game_params *p, random_state *rs, int nsecs)
2660 {
2661     time_t tt_start, tt_now, tt_last;
2662     int n = 0, nsolved = 0, nimpossible = 0, ret;
2663     char *grid, *clues;
2664
2665     tt_start = tt_last = time(NULL);
2666
2667     /* Currently this generates puzzles of any difficulty (trying to solve it
2668      * on the maximum difficulty level and not checking it's not too easy). */
2669     printf("Soak-testing a %dx%d grid (any difficulty)", p->w, p->h);
2670     if (nsecs > 0) printf(" for %d seconds", nsecs);
2671     printf(".\n");
2672
2673     p->nosolve = TRUE;
2674
2675     grid = snewn(p->w*p->h, char);
2676     clues = snewn(p->w*p->h, char);
2677
2678     while (1) {
2679         n += new_clues(p, rs, clues, grid); /* should be 1, with nosolve */
2680
2681         ret = pearl_solve(p->w, p->h, clues, grid, DIFF_TRICKY, FALSE);
2682         if (ret <= 0) nimpossible++;
2683         if (ret == 1) nsolved++;
2684
2685         tt_now = time(NULL);
2686         if (tt_now > tt_last) {
2687             tt_last = tt_now;
2688
2689             printf("%d total, %3.1f/s, ",
2690                    n, (double)n / ((double)tt_now - tt_start));
2691             pnum(nsolved, n, "solved"); printf(", ");
2692             printf("%3.1f/s", (double)nsolved / ((double)tt_now - tt_start));
2693             if (nimpossible > 0)
2694                 pnum(nimpossible, n, "impossible");
2695             printf("\n");
2696         }
2697         if (nsecs > 0 && (tt_now - tt_start) > nsecs) {
2698             printf("\n");
2699             break;
2700         }
2701     }
2702
2703     sfree(grid);
2704     sfree(clues);
2705 }
2706
2707 int main(int argc, const char *argv[])
2708 {
2709     game_params *p = NULL;
2710     random_state *rs = NULL;
2711     time_t seed = time(NULL);
2712     char *id = NULL;
2713     const char *err;
2714
2715     setvbuf(stdout, NULL, _IONBF, 0);
2716
2717     quis = argv[0];
2718
2719     while (--argc > 0) {
2720         char *p = (char*)(*++argv);
2721         if (!strcmp(p, "-e") || !strcmp(p, "--seed")) {
2722             seed = atoi(*++argv);
2723             argc--;
2724         } else if (*p == '-') {
2725             fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
2726             usage(stderr);
2727             exit(1);
2728         } else {
2729             id = p;
2730         }
2731     }
2732
2733     rs = random_new((void*)&seed, sizeof(time_t));
2734     p = default_params();
2735
2736     if (id) {
2737         if (strchr(id, ':')) {
2738             fprintf(stderr, "soak takes params only.\n");
2739             goto done;
2740         }
2741
2742         decode_params(p, id);
2743         err = validate_params(p, 1);
2744         if (err) {
2745             fprintf(stderr, "%s: %s", argv[0], err);
2746             goto done;
2747         }
2748
2749         start_soak(p, rs, 0); /* run forever */
2750     } else {
2751         int i;
2752
2753         for (i = 5; i <= 12; i++) {
2754             p->w = p->h = i;
2755             start_soak(p, rs, 5);
2756         }
2757     }
2758
2759 done:
2760     free_params(p);
2761     random_free(rs);
2762
2763     return 0;
2764 }
2765
2766 #endif
2767
2768 /* vim: set shiftwidth=4 tabstop=8: */