chiark / gitweb /
Update changelog for 20170923.ff218728-0+iwj2~3.gbpc58e0c release
[sgt-puzzles.git] / slant.c
1 /*
2  * slant.c: Puzzle from nikoli.co.jp involving drawing a diagonal
3  * line through each square of a grid.
4  */
5
6 /*
7  * In this puzzle you have a grid of squares, each of which must
8  * contain a diagonal line; you also have clue numbers placed at
9  * _points_ of that grid, which means there's a (w+1) x (h+1) array
10  * of possible clue positions.
11  * 
12  * I'm therefore going to adopt a rigid convention throughout this
13  * source file of using w and h for the dimensions of the grid of
14  * squares, and W and H for the dimensions of the grid of points.
15  * Thus, W == w+1 and H == h+1 always.
16  * 
17  * Clue arrays will be W*H `signed char's, and the clue at each
18  * point will be a number from 0 to 4, or -1 if there's no clue.
19  * 
20  * Solution arrays will be W*H `signed char's, and the number at
21  * each point will be +1 for a forward slash (/), -1 for a
22  * backslash (\), and 0 for unknown.
23  */
24
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <stdarg.h>
28 #include <string.h>
29 #include <assert.h>
30 #include <ctype.h>
31 #include <math.h>
32
33 #include "puzzles.h"
34
35 enum {
36     COL_BACKGROUND,
37     COL_GRID,
38     COL_INK,
39     COL_SLANT1,
40     COL_SLANT2,
41     COL_ERROR,
42     COL_CURSOR,
43     COL_FILLEDSQUARE,
44     NCOLOURS
45 };
46
47 /*
48  * In standalone solver mode, `verbose' is a variable which can be
49  * set by command-line option; in debugging mode it's simply always
50  * true.
51  */
52 #if defined STANDALONE_SOLVER
53 #define SOLVER_DIAGNOSTICS
54 int verbose = FALSE;
55 #elif defined SOLVER_DIAGNOSTICS
56 #define verbose TRUE
57 #endif
58
59 /*
60  * Difficulty levels. I do some macro ickery here to ensure that my
61  * enum and the various forms of my name list always match up.
62  */
63 #define DIFFLIST(A) \
64     A(EASY,Easy,e) \
65     A(HARD,Hard,h)
66 #define ENUM(upper,title,lower) DIFF_ ## upper,
67 #define TITLE(upper,title,lower) #title,
68 #define ENCODE(upper,title,lower) #lower
69 #define CONFIG(upper,title,lower) ":" #title
70 enum { DIFFLIST(ENUM) DIFFCOUNT };
71 static char const *const slant_diffnames[] = { DIFFLIST(TITLE) };
72 static char const slant_diffchars[] = DIFFLIST(ENCODE);
73 #define DIFFCONFIG DIFFLIST(CONFIG)
74
75 struct game_params {
76     int w, h, diff;
77 };
78
79 typedef struct game_clues {
80     int w, h;
81     signed char *clues;
82     int *tmpdsf;
83     int refcount;
84 } game_clues;
85
86 #define ERR_VERTEX 1
87 #define ERR_SQUARE 2
88
89 struct game_state {
90     struct game_params p;
91     game_clues *clues;
92     signed char *soln;
93     unsigned char *errors;
94     int completed;
95     int used_solve;                    /* used to suppress completion flash */
96 };
97
98 static game_params *default_params(void)
99 {
100     game_params *ret = snew(game_params);
101
102     ret->w = ret->h = 8;
103     ret->diff = DIFF_EASY;
104
105     return ret;
106 }
107
108 static const struct game_params slant_presets[] = {
109     {5, 5, DIFF_EASY},
110     {5, 5, DIFF_HARD},
111     {8, 8, DIFF_EASY},
112     {8, 8, DIFF_HARD},
113     {12, 10, DIFF_EASY},
114     {12, 10, DIFF_HARD},
115 };
116
117 static int game_fetch_preset(int i, char **name, game_params **params)
118 {
119     game_params *ret;
120     char str[80];
121
122     if (i < 0 || i >= lenof(slant_presets))
123         return FALSE;
124
125     ret = snew(game_params);
126     *ret = slant_presets[i];
127
128     sprintf(str, "%dx%d %s", ret->w, ret->h, slant_diffnames[ret->diff]);
129
130     *name = dupstr(str);
131     *params = ret;
132     return TRUE;
133 }
134
135 static void free_params(game_params *params)
136 {
137     sfree(params);
138 }
139
140 static game_params *dup_params(const game_params *params)
141 {
142     game_params *ret = snew(game_params);
143     *ret = *params;                    /* structure copy */
144     return ret;
145 }
146
147 static void decode_params(game_params *ret, char const *string)
148 {
149     ret->w = ret->h = atoi(string);
150     while (*string && isdigit((unsigned char)*string)) string++;
151     if (*string == 'x') {
152         string++;
153         ret->h = atoi(string);
154         while (*string && isdigit((unsigned char)*string)) string++;
155     }
156     if (*string == 'd') {
157         int i;
158         string++;
159         for (i = 0; i < DIFFCOUNT; i++)
160             if (*string == slant_diffchars[i])
161                 ret->diff = i;
162         if (*string) string++;
163     }
164 }
165
166 static char *encode_params(const game_params *params, int full)
167 {
168     char data[256];
169
170     sprintf(data, "%dx%d", params->w, params->h);
171     if (full)
172         sprintf(data + strlen(data), "d%c", slant_diffchars[params->diff]);
173
174     return dupstr(data);
175 }
176
177 static config_item *game_configure(const game_params *params)
178 {
179     config_item *ret;
180     char buf[80];
181
182     ret = snewn(4, config_item);
183
184     ret[0].name = "Width";
185     ret[0].type = C_STRING;
186     sprintf(buf, "%d", params->w);
187     ret[0].u.string.sval = dupstr(buf);
188
189     ret[1].name = "Height";
190     ret[1].type = C_STRING;
191     sprintf(buf, "%d", params->h);
192     ret[1].u.string.sval = dupstr(buf);
193
194     ret[2].name = "Difficulty";
195     ret[2].type = C_CHOICES;
196     ret[2].u.choices.choicenames = DIFFCONFIG;
197     ret[2].u.choices.selected = params->diff;
198
199     ret[3].name = NULL;
200     ret[3].type = C_END;
201
202     return ret;
203 }
204
205 static game_params *custom_params(const config_item *cfg)
206 {
207     game_params *ret = snew(game_params);
208
209     ret->w = atoi(cfg[0].u.string.sval);
210     ret->h = atoi(cfg[1].u.string.sval);
211     ret->diff = cfg[2].u.choices.selected;
212
213     return ret;
214 }
215
216 static const char *validate_params(const game_params *params, int full)
217 {
218     /*
219      * (At least at the time of writing this comment) The grid
220      * generator is actually capable of handling even zero grid
221      * dimensions without crashing. Puzzles with a zero-area grid
222      * are a bit boring, though, because they're already solved :-)
223      * And puzzles with a dimension of 1 can't be made Hard, which
224      * means the simplest thing is to forbid them altogether.
225      */
226
227     if (params->w < 2 || params->h < 2)
228         return "Width and height must both be at least two";
229
230     return NULL;
231 }
232
233 /*
234  * Scratch space for solver.
235  */
236 struct solver_scratch {
237     /*
238      * Disjoint set forest which tracks the connected sets of
239      * points.
240      */
241     int *connected;
242
243     /*
244      * Counts the number of possible exits from each connected set
245      * of points. (That is, the number of possible _simultaneous_
246      * exits: an unconnected point labelled 2 has an exit count of
247      * 2 even if all four possible edges are still under
248      * consideration.)
249      */
250     int *exits;
251
252     /*
253      * Tracks whether each connected set of points includes a
254      * border point.
255      */
256     unsigned char *border;
257
258     /*
259      * Another disjoint set forest. This one tracks _squares_ which
260      * are known to slant in the same direction.
261      */
262     int *equiv;
263
264     /*
265      * Stores slash values which we know for an equivalence class.
266      * When we fill in a square, we set slashval[canonify(x)] to
267      * the same value as soln[x], so that we can then spot other
268      * squares equivalent to it and fill them in immediately via
269      * their known equivalence.
270      */
271     signed char *slashval;
272
273     /*
274      * Stores possible v-shapes. This array is w by h in size, but
275      * not every bit of every entry is meaningful. The bits mean:
276      * 
277      *  - bit 0 for a square means that that square and the one to
278      *    its right might form a v-shape between them
279      *  - bit 1 for a square means that that square and the one to
280      *    its right might form a ^-shape between them
281      *  - bit 2 for a square means that that square and the one
282      *    below it might form a >-shape between them
283      *  - bit 3 for a square means that that square and the one
284      *    below it might form a <-shape between them
285      * 
286      * Any starting 1 or 3 clue rules out four bits in this array
287      * immediately; a 2 clue propagates any ruled-out bit past it
288      * (if the two squares on one side of a 2 cannot be a v-shape,
289      * then neither can the two on the other side be the same
290      * v-shape); we can rule out further bits during play using
291      * partially filled 2 clues; whenever a pair of squares is
292      * known not to be _either_ kind of v-shape, we can mark them
293      * as equivalent.
294      */
295     unsigned char *vbitmap;
296
297     /*
298      * Useful to have this information automatically passed to
299      * solver subroutines. (This pointer is not dynamically
300      * allocated by new_scratch and free_scratch.)
301      */
302     const signed char *clues;
303 };
304
305 static struct solver_scratch *new_scratch(int w, int h)
306 {
307     int W = w+1, H = h+1;
308     struct solver_scratch *ret = snew(struct solver_scratch);
309     ret->connected = snewn(W*H, int);
310     ret->exits = snewn(W*H, int);
311     ret->border = snewn(W*H, unsigned char);
312     ret->equiv = snewn(w*h, int);
313     ret->slashval = snewn(w*h, signed char);
314     ret->vbitmap = snewn(w*h, unsigned char);
315     return ret;
316 }
317
318 static void free_scratch(struct solver_scratch *sc)
319 {
320     sfree(sc->vbitmap);
321     sfree(sc->slashval);
322     sfree(sc->equiv);
323     sfree(sc->border);
324     sfree(sc->exits);
325     sfree(sc->connected);
326     sfree(sc);
327 }
328
329 /*
330  * Wrapper on dsf_merge() which updates the `exits' and `border'
331  * arrays.
332  */
333 static void merge_vertices(int *connected,
334                            struct solver_scratch *sc, int i, int j)
335 {
336     int exits = -1, border = FALSE;    /* initialise to placate optimiser */
337
338     if (sc) {
339         i = dsf_canonify(connected, i);
340         j = dsf_canonify(connected, j);
341
342         /*
343          * We have used one possible exit from each of the two
344          * classes. Thus, the viable exit count of the new class is
345          * the sum of the old exit counts minus two.
346          */
347         exits = sc->exits[i] + sc->exits[j] - 2;
348
349         border = sc->border[i] || sc->border[j];
350     }
351
352     dsf_merge(connected, i, j);
353
354     if (sc) {
355         i = dsf_canonify(connected, i);
356         sc->exits[i] = exits;
357         sc->border[i] = border;
358     }
359 }
360
361 /*
362  * Called when we have just blocked one way out of a particular
363  * point. If that point is a non-clue point (thus has a variable
364  * number of exits), we have therefore decreased its potential exit
365  * count, so we must decrement the exit count for the group as a
366  * whole.
367  */
368 static void decr_exits(struct solver_scratch *sc, int i)
369 {
370     if (sc->clues[i] < 0) {
371         i = dsf_canonify(sc->connected, i);
372         sc->exits[i]--;
373     }
374 }
375
376 static void fill_square(int w, int h, int x, int y, int v,
377                         signed char *soln,
378                         int *connected, struct solver_scratch *sc)
379 {
380     int W = w+1 /*, H = h+1 */;
381
382     assert(x >= 0 && x < w && y >= 0 && y < h);
383
384     if (soln[y*w+x] != 0) {
385         return;                        /* do nothing */
386     }
387
388 #ifdef SOLVER_DIAGNOSTICS
389     if (verbose)
390         printf("  placing %c in %d,%d\n", v == -1 ? '\\' : '/', x, y);
391 #endif
392
393     soln[y*w+x] = v;
394
395     if (sc) {
396         int c = dsf_canonify(sc->equiv, y*w+x);
397         sc->slashval[c] = v;
398     }
399
400     if (v < 0) {
401         merge_vertices(connected, sc, y*W+x, (y+1)*W+(x+1));
402         if (sc) {
403             decr_exits(sc, y*W+(x+1));
404             decr_exits(sc, (y+1)*W+x);
405         }
406     } else {
407         merge_vertices(connected, sc, y*W+(x+1), (y+1)*W+x);
408         if (sc) {
409             decr_exits(sc, y*W+x);
410             decr_exits(sc, (y+1)*W+(x+1));
411         }
412     }
413 }
414
415 static int vbitmap_clear(int w, int h, struct solver_scratch *sc,
416                          int x, int y, int vbits, const char *reason, ...)
417 {
418     int done_something = FALSE;
419     int vbit;
420
421     for (vbit = 1; vbit <= 8; vbit <<= 1)
422         if (vbits & sc->vbitmap[y*w+x] & vbit) {
423             done_something = TRUE;
424 #ifdef SOLVER_DIAGNOSTICS
425             if (verbose) {
426                 va_list ap;
427
428                 printf("ruling out %c shape at (%d,%d)-(%d,%d) (",
429                        "!v^!>!!!<"[vbit], x, y,
430                        x+((vbit&0x3)!=0), y+((vbit&0xC)!=0));
431
432                 va_start(ap, reason);
433                 vprintf(reason, ap);
434                 va_end(ap);
435
436                 printf(")\n");
437             }
438 #endif
439             sc->vbitmap[y*w+x] &= ~vbit;
440         }
441
442     return done_something;
443 }
444
445 /*
446  * Solver. Returns 0 for impossibility, 1 for success, 2 for
447  * ambiguity or failure to converge.
448  */
449 static int slant_solve(int w, int h, const signed char *clues,
450                        signed char *soln, struct solver_scratch *sc,
451                        int difficulty)
452 {
453     int W = w+1, H = h+1;
454     int x, y, i, j;
455     int done_something;
456
457     /*
458      * Clear the output.
459      */
460     memset(soln, 0, w*h);
461
462     sc->clues = clues;
463
464     /*
465      * Establish a disjoint set forest for tracking connectedness
466      * between grid points.
467      */
468     dsf_init(sc->connected, W*H);
469
470     /*
471      * Establish a disjoint set forest for tracking which squares
472      * are known to slant in the same direction.
473      */
474     dsf_init(sc->equiv, w*h);
475
476     /*
477      * Clear the slashval array.
478      */
479     memset(sc->slashval, 0, w*h);
480
481     /*
482      * Set up the vbitmap array. Initially all types of v are possible.
483      */
484     memset(sc->vbitmap, 0xF, w*h);
485
486     /*
487      * Initialise the `exits' and `border' arrays. These are used
488      * to do second-order loop avoidance: the dual of the no loops
489      * constraint is that every point must be somehow connected to
490      * the border of the grid (otherwise there would be a solid
491      * loop around it which prevented this).
492      * 
493      * I define a `dead end' to be a connected group of points
494      * which contains no border point, and which can form at most
495      * one new connection outside itself. Then I forbid placing an
496      * edge so that it connects together two dead-end groups, since
497      * this would yield a non-border-connected isolated subgraph
498      * with no further scope to extend it.
499      */
500     for (y = 0; y < H; y++)
501         for (x = 0; x < W; x++) {
502             if (y == 0 || y == H-1 || x == 0 || x == W-1)
503                 sc->border[y*W+x] = TRUE;
504             else
505                 sc->border[y*W+x] = FALSE;
506
507             if (clues[y*W+x] < 0)
508                 sc->exits[y*W+x] = 4;
509             else
510                 sc->exits[y*W+x] = clues[y*W+x];
511         }
512
513     /*
514      * Repeatedly try to deduce something until we can't.
515      */
516     do {
517         done_something = FALSE;
518
519         /*
520          * Any clue point with the number of remaining lines equal
521          * to zero or to the number of remaining undecided
522          * neighbouring squares can be filled in completely.
523          */
524         for (y = 0; y < H; y++)
525             for (x = 0; x < W; x++) {
526                 struct {
527                     int pos, slash;
528                 } neighbours[4];
529                 int nneighbours;
530                 int nu, nl, c, s, eq, eq2, last, meq, mj1, mj2;
531
532                 if ((c = clues[y*W+x]) < 0)
533                     continue;
534
535                 /*
536                  * We have a clue point. Start by listing its
537                  * neighbouring squares, in order around the point,
538                  * together with the type of slash that would be
539                  * required in that square to connect to the point.
540                  */
541                 nneighbours = 0;
542                 if (x > 0 && y > 0) {
543                     neighbours[nneighbours].pos = (y-1)*w+(x-1);
544                     neighbours[nneighbours].slash = -1;
545                     nneighbours++;
546                 }
547                 if (x > 0 && y < h) {
548                     neighbours[nneighbours].pos = y*w+(x-1);
549                     neighbours[nneighbours].slash = +1;
550                     nneighbours++;
551                 }
552                 if (x < w && y < h) {
553                     neighbours[nneighbours].pos = y*w+x;
554                     neighbours[nneighbours].slash = -1;
555                     nneighbours++;
556                 }
557                 if (x < w && y > 0) {
558                     neighbours[nneighbours].pos = (y-1)*w+x;
559                     neighbours[nneighbours].slash = +1;
560                     nneighbours++;
561                 }
562
563                 /*
564                  * Count up the number of undecided neighbours, and
565                  * also the number of lines already present.
566                  *
567                  * If we're not on DIFF_EASY, then in this loop we
568                  * also track whether we've seen two adjacent empty
569                  * squares belonging to the same equivalence class
570                  * (meaning they have the same type of slash). If
571                  * so, we count them jointly as one line.
572                  */
573                 nu = 0;
574                 nl = c;
575                 last = neighbours[nneighbours-1].pos;
576                 if (soln[last] == 0)
577                     eq = dsf_canonify(sc->equiv, last);
578                 else
579                     eq = -1;
580                 meq = mj1 = mj2 = -1;
581                 for (i = 0; i < nneighbours; i++) {
582                     j = neighbours[i].pos;
583                     s = neighbours[i].slash;
584                     if (soln[j] == 0) {
585                         nu++;          /* undecided */
586                         if (meq < 0 && difficulty > DIFF_EASY) {
587                             eq2 = dsf_canonify(sc->equiv, j);
588                             if (eq == eq2 && last != j) {
589                                 /*
590                                  * We've found an equivalent pair.
591                                  * Mark it. This also inhibits any
592                                  * further equivalence tracking
593                                  * around this square, since we can
594                                  * only handle one pair (and in
595                                  * particular we want to avoid
596                                  * being misled by two overlapping
597                                  * equivalence pairs).
598                                  */
599                                 meq = eq;
600                                 mj1 = last;
601                                 mj2 = j;
602                                 nl--;   /* count one line */
603                                 nu -= 2;   /* and lose two undecideds */
604                             } else
605                                 eq = eq2;
606                         }
607                     } else {
608                         eq = -1;
609                         if (soln[j] == s)
610                             nl--;      /* here's a line */
611                     }
612                     last = j;
613                 }
614
615                 /*
616                  * Check the counts.
617                  */
618                 if (nl < 0 || nl > nu) {
619                     /*
620                      * No consistent value for this at all!
621                      */
622 #ifdef SOLVER_DIAGNOSTICS
623                     if (verbose)
624                         printf("need %d / %d lines around clue point at %d,%d!\n",
625                                nl, nu, x, y);
626 #endif
627                     return 0;          /* impossible */
628                 }
629
630                 if (nu > 0 && (nl == 0 || nl == nu)) {
631 #ifdef SOLVER_DIAGNOSTICS
632                     if (verbose) {
633                         if (meq >= 0)
634                             printf("partially (since %d,%d == %d,%d) ",
635                                    mj1%w, mj1/w, mj2%w, mj2/w);
636                         printf("%s around clue point at %d,%d\n",
637                                nl ? "filling" : "emptying", x, y);
638                     }
639 #endif
640                     for (i = 0; i < nneighbours; i++) {
641                         j = neighbours[i].pos;
642                         s = neighbours[i].slash;
643                         if (soln[j] == 0 && j != mj1 && j != mj2)
644                             fill_square(w, h, j%w, j/w, (nl ? s : -s), soln,
645                                         sc->connected, sc);
646                     }
647
648                     done_something = TRUE;
649                 } else if (nu == 2 && nl == 1 && difficulty > DIFF_EASY) {
650                     /*
651                      * If we have precisely two undecided squares
652                      * and precisely one line to place between
653                      * them, _and_ those squares are adjacent, then
654                      * we can mark them as equivalent to one
655                      * another.
656                      * 
657                      * This even applies if meq >= 0: if we have a
658                      * 2 clue point and two of its neighbours are
659                      * already marked equivalent, we can indeed
660                      * mark the other two as equivalent.
661                      * 
662                      * We don't bother with this on DIFF_EASY,
663                      * since we wouldn't have used the results
664                      * anyway.
665                      */
666                     last = -1;
667                     for (i = 0; i < nneighbours; i++) {
668                         j = neighbours[i].pos;
669                         if (soln[j] == 0 && j != mj1 && j != mj2) {
670                             if (last < 0)
671                                 last = i;
672                             else if (last == i-1 || (last == 0 && i == 3))
673                                 break; /* found a pair */
674                         }
675                     }
676                     if (i < nneighbours) {
677                         int sv1, sv2;
678
679                         assert(last >= 0);
680                         /*
681                          * neighbours[last] and neighbours[i] are
682                          * the pair. Mark them equivalent.
683                          */
684 #ifdef SOLVER_DIAGNOSTICS
685                         if (verbose) {
686                             if (meq >= 0)
687                                 printf("since %d,%d == %d,%d, ",
688                                        mj1%w, mj1/w, mj2%w, mj2/w);
689                         }
690 #endif
691                         mj1 = neighbours[last].pos;
692                         mj2 = neighbours[i].pos;
693 #ifdef SOLVER_DIAGNOSTICS
694                         if (verbose)
695                             printf("clue point at %d,%d implies %d,%d == %d,"
696                                    "%d\n", x, y, mj1%w, mj1/w, mj2%w, mj2/w);
697 #endif
698                         mj1 = dsf_canonify(sc->equiv, mj1);
699                         sv1 = sc->slashval[mj1];
700                         mj2 = dsf_canonify(sc->equiv, mj2);
701                         sv2 = sc->slashval[mj2];
702                         if (sv1 != 0 && sv2 != 0 && sv1 != sv2) {
703 #ifdef SOLVER_DIAGNOSTICS
704                             if (verbose)
705                                 printf("merged two equivalence classes with"
706                                        " different slash values!\n");
707 #endif
708                             return 0;
709                         }
710                         sv1 = sv1 ? sv1 : sv2;
711                         dsf_merge(sc->equiv, mj1, mj2);
712                         mj1 = dsf_canonify(sc->equiv, mj1);
713                         sc->slashval[mj1] = sv1;
714                     }
715                 }
716             }
717
718         if (done_something)
719             continue;
720
721         /*
722          * Failing that, we now apply the second condition, which
723          * is that no square may be filled in such a way as to form
724          * a loop. Also in this loop (since it's over squares
725          * rather than points), we check slashval to see if we've
726          * already filled in another square in the same equivalence
727          * class.
728          * 
729          * The slashval check is disabled on DIFF_EASY, as is dead
730          * end avoidance. Only _immediate_ loop avoidance remains.
731          */
732         for (y = 0; y < h; y++)
733             for (x = 0; x < w; x++) {
734                 int fs, bs, v;
735                 int c1, c2;
736 #ifdef SOLVER_DIAGNOSTICS
737                 const char *reason = "<internal error>";
738 #endif
739
740                 if (soln[y*w+x])
741                     continue;          /* got this one already */
742
743                 fs = FALSE;
744                 bs = FALSE;
745
746                 if (difficulty > DIFF_EASY)
747                     v = sc->slashval[dsf_canonify(sc->equiv, y*w+x)];
748                 else
749                     v = 0;
750
751                 /*
752                  * Try to rule out connectivity between (x,y) and
753                  * (x+1,y+1); if successful, we will deduce that we
754                  * must have a forward slash.
755                  */
756                 c1 = dsf_canonify(sc->connected, y*W+x);
757                 c2 = dsf_canonify(sc->connected, (y+1)*W+(x+1));
758                 if (c1 == c2) {
759                     fs = TRUE;
760 #ifdef SOLVER_DIAGNOSTICS
761                     reason = "simple loop avoidance";
762 #endif
763                 }
764                 if (difficulty > DIFF_EASY &&
765                     !sc->border[c1] && !sc->border[c2] &&
766                     sc->exits[c1] <= 1 && sc->exits[c2] <= 1) {
767                     fs = TRUE;
768 #ifdef SOLVER_DIAGNOSTICS
769                     reason = "dead end avoidance";
770 #endif
771                 }
772                 if (v == +1) {
773                     fs = TRUE;
774 #ifdef SOLVER_DIAGNOSTICS
775                     reason = "equivalence to an already filled square";
776 #endif
777                 }
778
779                 /*
780                  * Now do the same between (x+1,y) and (x,y+1), to
781                  * see if we are required to have a backslash.
782                  */
783                 c1 = dsf_canonify(sc->connected, y*W+(x+1));
784                 c2 = dsf_canonify(sc->connected, (y+1)*W+x);
785                 if (c1 == c2) {
786                     bs = TRUE;
787 #ifdef SOLVER_DIAGNOSTICS
788                     reason = "simple loop avoidance";
789 #endif
790                 }
791                 if (difficulty > DIFF_EASY &&
792                     !sc->border[c1] && !sc->border[c2] &&
793                     sc->exits[c1] <= 1 && sc->exits[c2] <= 1) {
794                     bs = TRUE;
795 #ifdef SOLVER_DIAGNOSTICS
796                     reason = "dead end avoidance";
797 #endif
798                 }
799                 if (v == -1) {
800                     bs = TRUE;
801 #ifdef SOLVER_DIAGNOSTICS
802                     reason = "equivalence to an already filled square";
803 #endif
804                 }
805
806                 if (fs && bs) {
807                     /*
808                      * No consistent value for this at all!
809                      */
810 #ifdef SOLVER_DIAGNOSTICS
811                     if (verbose)
812                         printf("%d,%d has no consistent slash!\n", x, y);
813 #endif
814                     return 0;          /* impossible */
815                 }
816
817                 if (fs) {
818 #ifdef SOLVER_DIAGNOSTICS
819                     if (verbose)
820                         printf("employing %s\n", reason);
821 #endif
822                     fill_square(w, h, x, y, +1, soln, sc->connected, sc);
823                     done_something = TRUE;
824                 } else if (bs) {
825 #ifdef SOLVER_DIAGNOSTICS
826                     if (verbose)
827                         printf("employing %s\n", reason);
828 #endif
829                     fill_square(w, h, x, y, -1, soln, sc->connected, sc);
830                     done_something = TRUE;
831                 }
832             }
833
834         if (done_something)
835             continue;
836
837         /*
838          * Now see what we can do with the vbitmap array. All
839          * vbitmap deductions are disabled at Easy level.
840          */
841         if (difficulty <= DIFF_EASY)
842             continue;
843
844         for (y = 0; y < h; y++)
845             for (x = 0; x < w; x++) {
846                 int s, c;
847
848                 /*
849                  * Any line already placed in a square must rule
850                  * out any type of v which contradicts it.
851                  */
852                 if ((s = soln[y*w+x]) != 0) {
853                     if (x > 0)
854                         done_something |=
855                         vbitmap_clear(w, h, sc, x-1, y, (s < 0 ? 0x1 : 0x2),
856                                       "contradicts known edge at (%d,%d)",x,y);
857                     if (x+1 < w)
858                         done_something |=
859                         vbitmap_clear(w, h, sc, x, y, (s < 0 ? 0x2 : 0x1),
860                                       "contradicts known edge at (%d,%d)",x,y);
861                     if (y > 0)
862                         done_something |=
863                         vbitmap_clear(w, h, sc, x, y-1, (s < 0 ? 0x4 : 0x8),
864                                       "contradicts known edge at (%d,%d)",x,y);
865                     if (y+1 < h)
866                         done_something |=
867                         vbitmap_clear(w, h, sc, x, y, (s < 0 ? 0x8 : 0x4),
868                                       "contradicts known edge at (%d,%d)",x,y);
869                 }
870
871                 /*
872                  * If both types of v are ruled out for a pair of
873                  * adjacent squares, mark them as equivalent.
874                  */
875                 if (x+1 < w && !(sc->vbitmap[y*w+x] & 0x3)) {
876                     int n1 = y*w+x, n2 = y*w+(x+1);
877                     if (dsf_canonify(sc->equiv, n1) !=
878                         dsf_canonify(sc->equiv, n2)) {
879                         dsf_merge(sc->equiv, n1, n2);
880                         done_something = TRUE;
881 #ifdef SOLVER_DIAGNOSTICS
882                         if (verbose)
883                             printf("(%d,%d) and (%d,%d) must be equivalent"
884                                    " because both v-shapes are ruled out\n",
885                                    x, y, x+1, y);
886 #endif
887                     }
888                 }
889                 if (y+1 < h && !(sc->vbitmap[y*w+x] & 0xC)) {
890                     int n1 = y*w+x, n2 = (y+1)*w+x;
891                     if (dsf_canonify(sc->equiv, n1) !=
892                         dsf_canonify(sc->equiv, n2)) {
893                         dsf_merge(sc->equiv, n1, n2);
894                         done_something = TRUE;
895 #ifdef SOLVER_DIAGNOSTICS
896                         if (verbose)
897                             printf("(%d,%d) and (%d,%d) must be equivalent"
898                                    " because both v-shapes are ruled out\n",
899                                    x, y, x, y+1);
900 #endif
901                     }
902                 }
903
904                 /*
905                  * The remaining work in this loop only works
906                  * around non-edge clue points.
907                  */
908                 if (y == 0 || x == 0)
909                     continue;
910                 if ((c = clues[y*W+x]) < 0)
911                     continue;
912
913                 /*
914                  * x,y marks a clue point not on the grid edge. See
915                  * if this clue point allows us to rule out any v
916                  * shapes.
917                  */
918
919                 if (c == 1) {
920                     /*
921                      * A 1 clue can never have any v shape pointing
922                      * at it.
923                      */
924                     done_something |=
925                         vbitmap_clear(w, h, sc, x-1, y-1, 0x5,
926                                       "points at 1 clue at (%d,%d)", x, y);
927                     done_something |=
928                         vbitmap_clear(w, h, sc, x-1, y, 0x2,
929                                       "points at 1 clue at (%d,%d)", x, y);
930                     done_something |=
931                         vbitmap_clear(w, h, sc, x, y-1, 0x8,
932                                       "points at 1 clue at (%d,%d)", x, y);
933                 } else if (c == 3) {
934                     /*
935                      * A 3 clue can never have any v shape pointing
936                      * away from it.
937                      */
938                     done_something |=
939                         vbitmap_clear(w, h, sc, x-1, y-1, 0xA,
940                                       "points away from 3 clue at (%d,%d)", x, y);
941                     done_something |=
942                         vbitmap_clear(w, h, sc, x-1, y, 0x1,
943                                       "points away from 3 clue at (%d,%d)", x, y);
944                     done_something |=
945                         vbitmap_clear(w, h, sc, x, y-1, 0x4,
946                                       "points away from 3 clue at (%d,%d)", x, y);
947                 } else if (c == 2) {
948                     /*
949                      * If a 2 clue has any kind of v ruled out on
950                      * one side of it, the same v is ruled out on
951                      * the other side.
952                      */
953                     done_something |=
954                         vbitmap_clear(w, h, sc, x-1, y-1,
955                                       (sc->vbitmap[(y  )*w+(x-1)] & 0x3) ^ 0x3,
956                                       "propagated by 2 clue at (%d,%d)", x, y);
957                     done_something |=
958                         vbitmap_clear(w, h, sc, x-1, y-1,
959                                       (sc->vbitmap[(y-1)*w+(x  )] & 0xC) ^ 0xC,
960                                       "propagated by 2 clue at (%d,%d)", x, y);
961                     done_something |=
962                         vbitmap_clear(w, h, sc, x-1, y,
963                                       (sc->vbitmap[(y-1)*w+(x-1)] & 0x3) ^ 0x3,
964                                       "propagated by 2 clue at (%d,%d)", x, y);
965                     done_something |=
966                         vbitmap_clear(w, h, sc, x, y-1,
967                                       (sc->vbitmap[(y-1)*w+(x-1)] & 0xC) ^ 0xC,
968                                       "propagated by 2 clue at (%d,%d)", x, y);
969                 }
970
971 #undef CLEARBITS
972
973             }
974
975     } while (done_something);
976
977     /*
978      * Solver can make no more progress. See if the grid is full.
979      */
980     for (i = 0; i < w*h; i++)
981         if (!soln[i])
982             return 2;                  /* failed to converge */
983     return 1;                          /* success */
984 }
985
986 /*
987  * Filled-grid generator.
988  */
989 static void slant_generate(int w, int h, signed char *soln, random_state *rs)
990 {
991     int W = w+1, H = h+1;
992     int x, y, i;
993     int *connected, *indices;
994
995     /*
996      * Clear the output.
997      */
998     memset(soln, 0, w*h);
999
1000     /*
1001      * Establish a disjoint set forest for tracking connectedness
1002      * between grid points.
1003      */
1004     connected = snew_dsf(W*H);
1005
1006     /*
1007      * Prepare a list of the squares in the grid, and fill them in
1008      * in a random order.
1009      */
1010     indices = snewn(w*h, int);
1011     for (i = 0; i < w*h; i++)
1012         indices[i] = i;
1013     shuffle(indices, w*h, sizeof(*indices), rs);
1014
1015     /*
1016      * Fill in each one in turn.
1017      */
1018     for (i = 0; i < w*h; i++) {
1019         int fs, bs, v;
1020
1021         y = indices[i] / w;
1022         x = indices[i] % w;
1023
1024         fs = (dsf_canonify(connected, y*W+x) ==
1025               dsf_canonify(connected, (y+1)*W+(x+1)));
1026         bs = (dsf_canonify(connected, (y+1)*W+x) ==
1027               dsf_canonify(connected, y*W+(x+1)));
1028
1029         /*
1030          * It isn't possible to get into a situation where we
1031          * aren't allowed to place _either_ type of slash in a
1032          * square. Thus, filled-grid generation never has to
1033          * backtrack.
1034          * 
1035          * Proof (thanks to Gareth Taylor):
1036          * 
1037          * If it were possible, it would have to be because there
1038          * was an existing path (not using this square) between the
1039          * top-left and bottom-right corners of this square, and
1040          * another between the other two. These two paths would
1041          * have to cross at some point.
1042          * 
1043          * Obviously they can't cross in the middle of a square, so
1044          * they must cross by sharing a point in common. But this
1045          * isn't possible either: if you chessboard-colour all the
1046          * points on the grid, you find that any continuous
1047          * diagonal path is entirely composed of points of the same
1048          * colour. And one of our two hypothetical paths is between
1049          * two black points, and the other is between two white
1050          * points - therefore they can have no point in common. []
1051          */
1052         assert(!(fs && bs));
1053
1054         v = fs ? +1 : bs ? -1 : 2 * random_upto(rs, 2) - 1;
1055         fill_square(w, h, x, y, v, soln, connected, NULL);
1056     }
1057
1058     sfree(indices);
1059     sfree(connected);
1060 }
1061
1062 static char *new_game_desc(const game_params *params, random_state *rs,
1063                            char **aux, int interactive)
1064 {
1065     int w = params->w, h = params->h, W = w+1, H = h+1;
1066     signed char *soln, *tmpsoln, *clues;
1067     int *clueindices;
1068     struct solver_scratch *sc;
1069     int x, y, v, i, j;
1070     char *desc;
1071
1072     soln = snewn(w*h, signed char);
1073     tmpsoln = snewn(w*h, signed char);
1074     clues = snewn(W*H, signed char);
1075     clueindices = snewn(W*H, int);
1076     sc = new_scratch(w, h);
1077
1078     do {
1079         /*
1080          * Create the filled grid.
1081          */
1082         slant_generate(w, h, soln, rs);
1083
1084         /*
1085          * Fill in the complete set of clues.
1086          */
1087         for (y = 0; y < H; y++)
1088             for (x = 0; x < W; x++) {
1089                 v = 0;
1090
1091                 if (x > 0 && y > 0 && soln[(y-1)*w+(x-1)] == -1) v++;
1092                 if (x > 0 && y < h && soln[y*w+(x-1)] == +1) v++;
1093                 if (x < w && y > 0 && soln[(y-1)*w+x] == +1) v++;
1094                 if (x < w && y < h && soln[y*w+x] == -1) v++;
1095
1096                 clues[y*W+x] = v;
1097             }
1098
1099         /*
1100          * With all clue points filled in, all puzzles are easy: we can
1101          * simply process the clue points in lexicographic order, and
1102          * at each clue point we will always have at most one square
1103          * undecided, which we can then fill in uniquely.
1104          */
1105         assert(slant_solve(w, h, clues, tmpsoln, sc, DIFF_EASY) == 1);
1106
1107         /*
1108          * Remove as many clues as possible while retaining solubility.
1109          *
1110          * In DIFF_HARD mode, we prioritise the removal of obvious
1111          * starting points (4s, 0s, border 2s and corner 1s), on
1112          * the grounds that having as few of these as possible
1113          * seems like a good thing. In particular, we can often get
1114          * away without _any_ completely obvious starting points,
1115          * which is even better.
1116          */
1117         for (i = 0; i < W*H; i++)
1118             clueindices[i] = i;
1119         shuffle(clueindices, W*H, sizeof(*clueindices), rs);
1120         for (j = 0; j < 2; j++) {
1121             for (i = 0; i < W*H; i++) {
1122                 int pass, yb, xb;
1123
1124                 y = clueindices[i] / W;
1125                 x = clueindices[i] % W;
1126                 v = clues[y*W+x];
1127
1128                 /*
1129                  * Identify which pass we should process this point
1130                  * in. If it's an obvious start point, _or_ we're
1131                  * in DIFF_EASY, then it goes in pass 0; otherwise
1132                  * pass 1.
1133                  */
1134                 xb = (x == 0 || x == W-1);
1135                 yb = (y == 0 || y == H-1);
1136                 if (params->diff == DIFF_EASY || v == 4 || v == 0 ||
1137                     (v == 2 && (xb||yb)) || (v == 1 && xb && yb))
1138                     pass = 0;
1139                 else
1140                     pass = 1;
1141
1142                 if (pass == j) {
1143                     clues[y*W+x] = -1;
1144                     if (slant_solve(w, h, clues, tmpsoln, sc,
1145                                     params->diff) != 1)
1146                         clues[y*W+x] = v;              /* put it back */
1147                 }
1148             }
1149         }
1150
1151         /*
1152          * And finally, verify that the grid is of _at least_ the
1153          * requested difficulty, by running the solver one level
1154          * down and verifying that it can't manage it.
1155          */
1156     } while (params->diff > 0 &&
1157              slant_solve(w, h, clues, tmpsoln, sc, params->diff - 1) <= 1);
1158
1159     /*
1160      * Now we have the clue set as it will be presented to the
1161      * user. Encode it in a game desc.
1162      */
1163     {
1164         char *p;
1165         int run, i;
1166
1167         desc = snewn(W*H+1, char);
1168         p = desc;
1169         run = 0;
1170         for (i = 0; i <= W*H; i++) {
1171             int n = (i < W*H ? clues[i] : -2);
1172
1173             if (n == -1)
1174                 run++;
1175             else {
1176                 if (run) {
1177                     while (run > 0) {
1178                         int c = 'a' - 1 + run;
1179                         if (run > 26)
1180                             c = 'z';
1181                         *p++ = c;
1182                         run -= c - ('a' - 1);
1183                     }
1184                 }
1185                 if (n >= 0)
1186                     *p++ = '0' + n;
1187                 run = 0;
1188             }
1189         }
1190         assert(p - desc <= W*H);
1191         *p++ = '\0';
1192         desc = sresize(desc, p - desc, char);
1193     }
1194
1195     /*
1196      * Encode the solution as an aux_info.
1197      */
1198     {
1199         char *auxbuf;
1200         *aux = auxbuf = snewn(w*h+1, char);
1201         for (i = 0; i < w*h; i++)
1202             auxbuf[i] = soln[i] < 0 ? '\\' : '/';
1203         auxbuf[w*h] = '\0';
1204     }
1205
1206     free_scratch(sc);
1207     sfree(clueindices);
1208     sfree(clues);
1209     sfree(tmpsoln);
1210     sfree(soln);
1211
1212     return desc;
1213 }
1214
1215 static const char *validate_desc(const game_params *params, const char *desc)
1216 {
1217     int w = params->w, h = params->h, W = w+1, H = h+1;
1218     int area = W*H;
1219     int squares = 0;
1220
1221     while (*desc) {
1222         int n = *desc++;
1223         if (n >= 'a' && n <= 'z') {
1224             squares += n - 'a' + 1;
1225         } else if (n >= '0' && n <= '4') {
1226             squares++;
1227         } else
1228             return "Invalid character in game description";
1229     }
1230
1231     if (squares < area)
1232         return "Not enough data to fill grid";
1233
1234     if (squares > area)
1235         return "Too much data to fit in grid";
1236
1237     return NULL;
1238 }
1239
1240 static game_state *new_game(midend *me, const game_params *params,
1241                             const char *desc)
1242 {
1243     int w = params->w, h = params->h, W = w+1, H = h+1;
1244     game_state *state = snew(game_state);
1245     int area = W*H;
1246     int squares = 0;
1247
1248     state->p = *params;
1249     state->soln = snewn(w*h, signed char);
1250     memset(state->soln, 0, w*h);
1251     state->completed = state->used_solve = FALSE;
1252     state->errors = snewn(W*H, unsigned char);
1253     memset(state->errors, 0, W*H);
1254
1255     state->clues = snew(game_clues);
1256     state->clues->w = w;
1257     state->clues->h = h;
1258     state->clues->clues = snewn(W*H, signed char);
1259     state->clues->refcount = 1;
1260     state->clues->tmpdsf = snewn(W*H*2+W+H, int);
1261     memset(state->clues->clues, -1, W*H);
1262     while (*desc) {
1263         int n = *desc++;
1264         if (n >= 'a' && n <= 'z') {
1265             squares += n - 'a' + 1;
1266         } else if (n >= '0' && n <= '4') {
1267             state->clues->clues[squares++] = n - '0';
1268         } else
1269             assert(!"can't get here");
1270     }
1271     assert(squares == area);
1272
1273     return state;
1274 }
1275
1276 static game_state *dup_game(const game_state *state)
1277 {
1278     int w = state->p.w, h = state->p.h, W = w+1, H = h+1;
1279     game_state *ret = snew(game_state);
1280
1281     ret->p = state->p;
1282     ret->clues = state->clues;
1283     ret->clues->refcount++;
1284     ret->completed = state->completed;
1285     ret->used_solve = state->used_solve;
1286
1287     ret->soln = snewn(w*h, signed char);
1288     memcpy(ret->soln, state->soln, w*h);
1289
1290     ret->errors = snewn(W*H, unsigned char);
1291     memcpy(ret->errors, state->errors, W*H);
1292
1293     return ret;
1294 }
1295
1296 static void free_game(game_state *state)
1297 {
1298     sfree(state->errors);
1299     sfree(state->soln);
1300     assert(state->clues);
1301     if (--state->clues->refcount <= 0) {
1302         sfree(state->clues->clues);
1303         sfree(state->clues->tmpdsf);
1304         sfree(state->clues);
1305     }
1306     sfree(state);
1307 }
1308
1309 /*
1310  * Utility function to return the current degree of a vertex. If
1311  * `anti' is set, it returns the number of filled-in edges
1312  * surrounding the point which _don't_ connect to it; thus 4 minus
1313  * its anti-degree is the maximum degree it could have if all the
1314  * empty spaces around it were filled in.
1315  * 
1316  * (Yes, _4_ minus its anti-degree even if it's a border vertex.)
1317  * 
1318  * If ret > 0, *sx and *sy are set to the coordinates of one of the
1319  * squares that contributed to it.
1320  */
1321 static int vertex_degree(int w, int h, signed char *soln, int x, int y,
1322                          int anti, int *sx, int *sy)
1323 {
1324     int ret = 0;
1325
1326     assert(x >= 0 && x <= w && y >= 0 && y <= h);
1327     if (x > 0 && y > 0 && soln[(y-1)*w+(x-1)] - anti < 0) {
1328         if (sx) *sx = x-1;
1329         if (sy) *sy = y-1;
1330         ret++;
1331     }
1332     if (x > 0 && y < h && soln[y*w+(x-1)] + anti > 0) {
1333         if (sx) *sx = x-1;
1334         if (sy) *sy = y;
1335         ret++;
1336     }
1337     if (x < w && y > 0 && soln[(y-1)*w+x] + anti > 0) {
1338         if (sx) *sx = x;
1339         if (sy) *sy = y-1;
1340         ret++;
1341     }
1342     if (x < w && y < h && soln[y*w+x] - anti < 0) {
1343         if (sx) *sx = x;
1344         if (sy) *sy = y;
1345         ret++;
1346     }
1347
1348     return anti ? 4 - ret : ret;
1349 }
1350
1351 struct slant_neighbour_ctx {
1352     const game_state *state;
1353     int i, n, neighbours[4];
1354 };
1355 static int slant_neighbour(int vertex, void *vctx)
1356 {
1357     struct slant_neighbour_ctx *ctx = (struct slant_neighbour_ctx *)vctx;
1358
1359     if (vertex >= 0) {
1360         int w = ctx->state->p.w, h = ctx->state->p.h, W = w+1;
1361         int x = vertex % W, y = vertex / W;
1362         ctx->n = ctx->i = 0;
1363         if (x < w && y < h && ctx->state->soln[y*w+x] < 0)
1364             ctx->neighbours[ctx->n++] = (y+1)*W+(x+1);
1365         if (x > 0 && y > 0 && ctx->state->soln[(y-1)*w+(x-1)] < 0)
1366             ctx->neighbours[ctx->n++] = (y-1)*W+(x-1);
1367         if (x > 0 && y < h && ctx->state->soln[y*w+(x-1)] > 0)
1368             ctx->neighbours[ctx->n++] = (y+1)*W+(x-1);
1369         if (x < w && y > 0 && ctx->state->soln[(y-1)*w+x] > 0)
1370             ctx->neighbours[ctx->n++] = (y-1)*W+(x+1);
1371     }
1372
1373     if (ctx->i < ctx->n)
1374         return ctx->neighbours[ctx->i++];
1375     else
1376         return -1;
1377 }
1378
1379 static int check_completion(game_state *state)
1380 {
1381     int w = state->p.w, h = state->p.h, W = w+1, H = h+1;
1382     int x, y, err = FALSE;
1383
1384     memset(state->errors, 0, W*H);
1385
1386     /*
1387      * Detect and error-highlight loops in the grid.
1388      */
1389     {
1390         struct findloopstate *fls = findloop_new_state(W*H);
1391         struct slant_neighbour_ctx ctx;
1392         ctx.state = state;
1393
1394         if (findloop_run(fls, W*H, slant_neighbour, &ctx))
1395             err = TRUE;
1396         for (y = 0; y < h; y++) {
1397             for (x = 0; x < w; x++) {
1398                 int u, v;
1399                 if (state->soln[y*w+x] == 0) {
1400                     continue;
1401                 } else if (state->soln[y*w+x] > 0) {
1402                     u = y*W+(x+1);
1403                     v = (y+1)*W+x;
1404                 } else {
1405                     u = (y+1)*W+(x+1);
1406                     v = y*W+x;
1407                 }
1408                 if (findloop_is_loop_edge(fls, u, v))
1409                     state->errors[y*W+x] |= ERR_SQUARE;
1410             }
1411         }
1412
1413         findloop_free_state(fls);
1414     }
1415
1416     /*
1417      * Now go through and check the degree of each clue vertex, and
1418      * mark it with ERR_VERTEX if it cannot be fulfilled.
1419      */
1420     for (y = 0; y < H; y++)
1421         for (x = 0; x < W; x++) {
1422             int c;
1423
1424             if ((c = state->clues->clues[y*W+x]) < 0)
1425                 continue;
1426
1427             /*
1428              * Check to see if there are too many connections to
1429              * this vertex _or_ too many non-connections. Either is
1430              * grounds for marking the vertex as erroneous.
1431              */
1432             if (vertex_degree(w, h, state->soln, x, y,
1433                               FALSE, NULL, NULL) > c ||
1434                 vertex_degree(w, h, state->soln, x, y,
1435                               TRUE, NULL, NULL) > 4-c) {
1436                 state->errors[y*W+x] |= ERR_VERTEX;
1437                 err = TRUE;
1438             }
1439         }
1440
1441     /*
1442      * Now our actual victory condition is that (a) none of the
1443      * above code marked anything as erroneous, and (b) every
1444      * square has an edge in it.
1445      */
1446
1447     if (err)
1448         return FALSE;
1449
1450     for (y = 0; y < h; y++)
1451         for (x = 0; x < w; x++)
1452             if (state->soln[y*w+x] == 0)
1453                 return FALSE;
1454
1455     return TRUE;
1456 }
1457
1458 static char *solve_game(const game_state *state, const game_state *currstate,
1459                         const char *aux, const char **error)
1460 {
1461     int w = state->p.w, h = state->p.h;
1462     signed char *soln;
1463     int bs, ret;
1464     int free_soln = FALSE;
1465     char *move, buf[80];
1466     int movelen, movesize;
1467     int x, y;
1468
1469     if (aux) {
1470         /*
1471          * If we already have the solution, save ourselves some
1472          * time.
1473          */
1474         soln = (signed char *)aux;
1475         bs = (signed char)'\\';
1476         free_soln = FALSE;
1477     } else {
1478         struct solver_scratch *sc = new_scratch(w, h);
1479         soln = snewn(w*h, signed char);
1480         bs = -1;
1481         ret = slant_solve(w, h, state->clues->clues, soln, sc, DIFF_HARD);
1482         free_scratch(sc);
1483         if (ret != 1) {
1484             sfree(soln);
1485             if (ret == 0)
1486                 *error = "This puzzle is not self-consistent";
1487             else
1488                 *error = "Unable to find a unique solution for this puzzle";
1489             return NULL;
1490         }
1491         free_soln = TRUE;
1492     }
1493
1494     /*
1495      * Construct a move string which turns the current state into
1496      * the solved state.
1497      */
1498     movesize = 256;
1499     move = snewn(movesize, char);
1500     movelen = 0;
1501     move[movelen++] = 'S';
1502     move[movelen] = '\0';
1503     for (y = 0; y < h; y++)
1504         for (x = 0; x < w; x++) {
1505             int v = (soln[y*w+x] == bs ? -1 : +1);
1506             if (state->soln[y*w+x] != v) {
1507                 int len = sprintf(buf, ";%c%d,%d", (int)(v < 0 ? '\\' : '/'), x, y);
1508                 if (movelen + len >= movesize) {
1509                     movesize = movelen + len + 256;
1510                     move = sresize(move, movesize, char);
1511                 }
1512                 strcpy(move + movelen, buf);
1513                 movelen += len;
1514             }
1515         }
1516
1517     if (free_soln)
1518         sfree(soln);
1519
1520     return move;
1521 }
1522
1523 static int game_can_format_as_text_now(const game_params *params)
1524 {
1525     return TRUE;
1526 }
1527
1528 static char *game_text_format(const game_state *state)
1529 {
1530     int w = state->p.w, h = state->p.h, W = w+1, H = h+1;
1531     int x, y, len;
1532     char *ret, *p;
1533
1534     /*
1535      * There are h+H rows of w+W columns.
1536      */
1537     len = (h+H) * (w+W+1) + 1;
1538     ret = snewn(len, char);
1539     p = ret;
1540
1541     for (y = 0; y < H; y++) {
1542         for (x = 0; x < W; x++) {
1543             if (state->clues->clues[y*W+x] >= 0)
1544                 *p++ = state->clues->clues[y*W+x] + '0';
1545             else
1546                 *p++ = '+';
1547             if (x < w)
1548                 *p++ = '-';
1549         }
1550         *p++ = '\n';
1551         if (y < h) {
1552             for (x = 0; x < W; x++) {
1553                 *p++ = '|';
1554                 if (x < w) {
1555                     if (state->soln[y*w+x] != 0)
1556                         *p++ = (state->soln[y*w+x] < 0 ? '\\' : '/');
1557                     else
1558                         *p++ = ' ';
1559                 }
1560             }
1561             *p++ = '\n';
1562         }
1563     }
1564     *p++ = '\0';
1565
1566     assert(p - ret == len);
1567     return ret;
1568 }
1569
1570 struct game_ui {
1571     int cur_x, cur_y, cur_visible;
1572 };
1573
1574 static game_ui *new_ui(const game_state *state)
1575 {
1576     game_ui *ui = snew(game_ui);
1577     ui->cur_x = ui->cur_y = ui->cur_visible = 0;
1578     return ui;
1579 }
1580
1581 static void free_ui(game_ui *ui)
1582 {
1583     sfree(ui);
1584 }
1585
1586 static char *encode_ui(const game_ui *ui)
1587 {
1588     return NULL;
1589 }
1590
1591 static void decode_ui(game_ui *ui, const char *encoding)
1592 {
1593 }
1594
1595 static void game_changed_state(game_ui *ui, const game_state *oldstate,
1596                                const game_state *newstate)
1597 {
1598 }
1599
1600 #define PREFERRED_TILESIZE 32
1601 #define TILESIZE (ds->tilesize)
1602 #define BORDER TILESIZE
1603 #define CLUE_RADIUS (TILESIZE / 3)
1604 #define CLUE_TEXTSIZE (TILESIZE / 2)
1605 #define COORD(x)  ( (x) * TILESIZE + BORDER )
1606 #define FROMCOORD(x)  ( ((x) - BORDER + TILESIZE) / TILESIZE - 1 )
1607
1608 #define FLASH_TIME 0.30F
1609
1610 /*
1611  * Bit fields in the `grid' and `todraw' elements of the drawstate.
1612  */
1613 #define BACKSLASH 0x00000001L
1614 #define FORWSLASH 0x00000002L
1615 #define L_T       0x00000004L
1616 #define ERR_L_T   0x00000008L
1617 #define L_B       0x00000010L
1618 #define ERR_L_B   0x00000020L
1619 #define T_L       0x00000040L
1620 #define ERR_T_L   0x00000080L
1621 #define T_R       0x00000100L
1622 #define ERR_T_R   0x00000200L
1623 #define C_TL      0x00000400L
1624 #define ERR_C_TL  0x00000800L
1625 #define FLASH     0x00001000L
1626 #define ERRSLASH  0x00002000L
1627 #define ERR_TL    0x00004000L
1628 #define ERR_TR    0x00008000L
1629 #define ERR_BL    0x00010000L
1630 #define ERR_BR    0x00020000L
1631 #define CURSOR    0x00040000L
1632
1633 struct game_drawstate {
1634     int tilesize;
1635     int started;
1636     long *grid;
1637     long *todraw;
1638 };
1639
1640 static char *interpret_move(const game_state *state, game_ui *ui,
1641                             const game_drawstate *ds,
1642                             int x, int y, int button)
1643 {
1644     int w = state->p.w, h = state->p.h;
1645     int v;
1646     char buf[80];
1647     enum { CLOCKWISE, ANTICLOCKWISE, NONE } action = NONE;
1648
1649     if (button == LEFT_BUTTON || button == RIGHT_BUTTON) {
1650         /*
1651          * This is an utterly awful hack which I should really sort out
1652          * by means of a proper configuration mechanism. One Slant
1653          * player has observed that they prefer the mouse buttons to
1654          * function exactly the opposite way round, so here's a
1655          * mechanism for environment-based configuration. I cache the
1656          * result in a global variable - yuck! - to avoid repeated
1657          * lookups.
1658          */
1659         {
1660             static int swap_buttons = -1;
1661             if (swap_buttons < 0) {
1662                 char *env = getenv("SLANT_SWAP_BUTTONS");
1663                 swap_buttons = (env && (env[0] == 'y' || env[0] == 'Y'));
1664             }
1665             if (swap_buttons) {
1666                 if (button == LEFT_BUTTON)
1667                     button = RIGHT_BUTTON;
1668                 else
1669                     button = LEFT_BUTTON;
1670             }
1671         }
1672         action = (button == LEFT_BUTTON) ? CLOCKWISE : ANTICLOCKWISE;
1673
1674         x = FROMCOORD(x);
1675         y = FROMCOORD(y);
1676         if (x < 0 || y < 0 || x >= w || y >= h)
1677             return NULL;
1678         ui->cur_visible = 0;
1679     } else if (IS_CURSOR_SELECT(button)) {
1680         if (!ui->cur_visible) {
1681             ui->cur_visible = 1;
1682             return UI_UPDATE;
1683         }
1684         x = ui->cur_x;
1685         y = ui->cur_y;
1686
1687         action = (button == CURSOR_SELECT2) ? ANTICLOCKWISE : CLOCKWISE;
1688     } else if (IS_CURSOR_MOVE(button)) {
1689         move_cursor(button, &ui->cur_x, &ui->cur_y, w, h, 0);
1690         ui->cur_visible = 1;
1691         return UI_UPDATE;
1692     } else if (button == '\\' || button == '\b' || button == '/') {
1693         int x = ui->cur_x, y = ui->cur_y;
1694         if (button == ("\\" "\b" "/")[state->soln[y*w + x] + 1]) return NULL;
1695         sprintf(buf, "%c%d,%d", button == '\b' ? 'C' : button, x, y);
1696         return dupstr(buf);
1697     }
1698
1699     if (action != NONE) {
1700         if (action == CLOCKWISE) {
1701             /*
1702              * Left-clicking cycles blank -> \ -> / -> blank.
1703              */
1704             v = state->soln[y*w+x] - 1;
1705             if (v == -2)
1706                 v = +1;
1707         } else {
1708             /*
1709              * Right-clicking cycles blank -> / -> \ -> blank.
1710              */
1711             v = state->soln[y*w+x] + 1;
1712             if (v == +2)
1713                 v = -1;
1714         }
1715
1716         sprintf(buf, "%c%d,%d", (int)(v==-1 ? '\\' : v==+1 ? '/' : 'C'), x, y);
1717         return dupstr(buf);
1718     }
1719
1720     return NULL;
1721 }
1722
1723 static game_state *execute_move(const game_state *state, const char *move)
1724 {
1725     int w = state->p.w, h = state->p.h;
1726     char c;
1727     int x, y, n;
1728     game_state *ret = dup_game(state);
1729
1730     while (*move) {
1731         c = *move;
1732         if (c == 'S') {
1733             ret->used_solve = TRUE;
1734             move++;
1735         } else if (c == '\\' || c == '/' || c == 'C') {
1736             move++;
1737             if (sscanf(move, "%d,%d%n", &x, &y, &n) != 2 ||
1738                 x < 0 || y < 0 || x >= w || y >= h) {
1739                 free_game(ret);
1740                 return NULL;
1741             }
1742             ret->soln[y*w+x] = (c == '\\' ? -1 : c == '/' ? +1 : 0);
1743             move += n;
1744         } else {
1745             free_game(ret);
1746             return NULL;
1747         }
1748         if (*move == ';')
1749             move++;
1750         else if (*move) {
1751             free_game(ret);
1752             return NULL;
1753         }
1754     }
1755
1756     /*
1757      * We never clear the `completed' flag, but we must always
1758      * re-run the completion check because it also highlights
1759      * errors in the grid.
1760      */
1761     ret->completed = check_completion(ret) || ret->completed;
1762
1763     return ret;
1764 }
1765
1766 /* ----------------------------------------------------------------------
1767  * Drawing routines.
1768  */
1769
1770 static void game_compute_size(const game_params *params, int tilesize,
1771                               int *x, int *y)
1772 {
1773     /* fool the macros */
1774     struct dummy { int tilesize; } dummy, *ds = &dummy;
1775     dummy.tilesize = tilesize;
1776
1777     *x = 2 * BORDER + params->w * TILESIZE + 1;
1778     *y = 2 * BORDER + params->h * TILESIZE + 1;
1779 }
1780
1781 static void game_set_size(drawing *dr, game_drawstate *ds,
1782                           const game_params *params, int tilesize)
1783 {
1784     ds->tilesize = tilesize;
1785 }
1786
1787 static float *game_colours(frontend *fe, int *ncolours)
1788 {
1789     float *ret = snewn(3 * NCOLOURS, float);
1790
1791     /* CURSOR colour is a background highlight. */
1792     game_mkhighlight(fe, ret, COL_BACKGROUND, COL_CURSOR, COL_FILLEDSQUARE);
1793
1794     ret[COL_GRID * 3 + 0] = ret[COL_BACKGROUND * 3 + 0] * 0.7F;
1795     ret[COL_GRID * 3 + 1] = ret[COL_BACKGROUND * 3 + 1] * 0.7F;
1796     ret[COL_GRID * 3 + 2] = ret[COL_BACKGROUND * 3 + 2] * 0.7F;
1797
1798     ret[COL_INK * 3 + 0] = 0.0F;
1799     ret[COL_INK * 3 + 1] = 0.0F;
1800     ret[COL_INK * 3 + 2] = 0.0F;
1801
1802     ret[COL_SLANT1 * 3 + 0] = 0.0F;
1803     ret[COL_SLANT1 * 3 + 1] = 0.0F;
1804     ret[COL_SLANT1 * 3 + 2] = 0.0F;
1805
1806     ret[COL_SLANT2 * 3 + 0] = 0.0F;
1807     ret[COL_SLANT2 * 3 + 1] = 0.0F;
1808     ret[COL_SLANT2 * 3 + 2] = 0.0F;
1809
1810     ret[COL_ERROR * 3 + 0] = 1.0F;
1811     ret[COL_ERROR * 3 + 1] = 0.0F;
1812     ret[COL_ERROR * 3 + 2] = 0.0F;
1813
1814     *ncolours = NCOLOURS;
1815     return ret;
1816 }
1817
1818 static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
1819 {
1820     int w = state->p.w, h = state->p.h;
1821     int i;
1822     struct game_drawstate *ds = snew(struct game_drawstate);
1823
1824     ds->tilesize = 0;
1825     ds->started = FALSE;
1826     ds->grid = snewn((w+2)*(h+2), long);
1827     ds->todraw = snewn((w+2)*(h+2), long);
1828     for (i = 0; i < (w+2)*(h+2); i++)
1829         ds->grid[i] = ds->todraw[i] = -1;
1830
1831     return ds;
1832 }
1833
1834 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
1835 {
1836     sfree(ds->todraw);
1837     sfree(ds->grid);
1838     sfree(ds);
1839 }
1840
1841 static void draw_clue(drawing *dr, game_drawstate *ds,
1842                       int x, int y, long v, long err, int bg, int colour)
1843 {
1844     char p[2];
1845     int ccol = colour >= 0 ? colour : ((x ^ y) & 1) ? COL_SLANT1 : COL_SLANT2;
1846     int tcol = colour >= 0 ? colour : err ? COL_ERROR : COL_INK;
1847
1848     if (v < 0)
1849         return;
1850
1851     p[0] = (char)v + '0';
1852     p[1] = '\0';
1853     draw_circle(dr, COORD(x), COORD(y), CLUE_RADIUS,
1854                 bg >= 0 ? bg : COL_BACKGROUND, ccol);
1855     draw_text(dr, COORD(x), COORD(y), FONT_VARIABLE,
1856               CLUE_TEXTSIZE, ALIGN_VCENTRE|ALIGN_HCENTRE, tcol, p);
1857 }
1858
1859 static void draw_tile(drawing *dr, game_drawstate *ds, game_clues *clues,
1860                       int x, int y, long v)
1861 {
1862     int w = clues->w, h = clues->h, W = w+1 /*, H = h+1 */;
1863     int chesscolour = (x ^ y) & 1;
1864     int fscol = chesscolour ? COL_SLANT2 : COL_SLANT1;
1865     int bscol = chesscolour ? COL_SLANT1 : COL_SLANT2;
1866
1867     clip(dr, COORD(x), COORD(y), TILESIZE, TILESIZE);
1868
1869     draw_rect(dr, COORD(x), COORD(y), TILESIZE, TILESIZE,
1870               (v & FLASH) ? COL_GRID :
1871               (v & CURSOR) ? COL_CURSOR :
1872               (v & (BACKSLASH | FORWSLASH)) ? COL_FILLEDSQUARE :
1873               COL_BACKGROUND);
1874
1875     /*
1876      * Draw the grid lines.
1877      */
1878     if (x >= 0 && x < w && y >= 0)
1879         draw_rect(dr, COORD(x), COORD(y), TILESIZE+1, 1, COL_GRID);
1880     if (x >= 0 && x < w && y < h)
1881         draw_rect(dr, COORD(x), COORD(y+1), TILESIZE+1, 1, COL_GRID);
1882     if (y >= 0 && y < h && x >= 0)
1883         draw_rect(dr, COORD(x), COORD(y), 1, TILESIZE+1, COL_GRID);
1884     if (y >= 0 && y < h && x < w)
1885         draw_rect(dr, COORD(x+1), COORD(y), 1, TILESIZE+1, COL_GRID);
1886     if (x == -1 && y == -1)
1887         draw_rect(dr, COORD(x+1), COORD(y+1), 1, 1, COL_GRID);
1888     if (x == -1 && y == h)
1889         draw_rect(dr, COORD(x+1), COORD(y), 1, 1, COL_GRID);
1890     if (x == w && y == -1)
1891         draw_rect(dr, COORD(x), COORD(y+1), 1, 1, COL_GRID);
1892     if (x == w && y == h)
1893         draw_rect(dr, COORD(x), COORD(y), 1, 1, COL_GRID);
1894
1895     /*
1896      * Draw the slash.
1897      */
1898     if (v & BACKSLASH) {
1899         int scol = (v & ERRSLASH) ? COL_ERROR : bscol;
1900         draw_line(dr, COORD(x), COORD(y), COORD(x+1), COORD(y+1), scol);
1901         draw_line(dr, COORD(x)+1, COORD(y), COORD(x+1), COORD(y+1)-1,
1902                   scol);
1903         draw_line(dr, COORD(x), COORD(y)+1, COORD(x+1)-1, COORD(y+1),
1904                   scol);
1905     } else if (v & FORWSLASH) {
1906         int scol = (v & ERRSLASH) ? COL_ERROR : fscol;
1907         draw_line(dr, COORD(x+1), COORD(y), COORD(x), COORD(y+1), scol);
1908         draw_line(dr, COORD(x+1)-1, COORD(y), COORD(x), COORD(y+1)-1,
1909                   scol);
1910         draw_line(dr, COORD(x+1), COORD(y)+1, COORD(x)+1, COORD(y+1),
1911                   scol);
1912     }
1913
1914     /*
1915      * Draw dots on the grid corners that appear if a slash is in a
1916      * neighbouring cell.
1917      */
1918     if (v & (L_T | BACKSLASH))
1919         draw_rect(dr, COORD(x), COORD(y)+1, 1, 1,
1920                   (v & ERR_L_T ? COL_ERROR : bscol));
1921     if (v & (L_B | FORWSLASH))
1922         draw_rect(dr, COORD(x), COORD(y+1)-1, 1, 1,
1923                   (v & ERR_L_B ? COL_ERROR : fscol));
1924     if (v & (T_L | BACKSLASH))
1925         draw_rect(dr, COORD(x)+1, COORD(y), 1, 1,
1926                   (v & ERR_T_L ? COL_ERROR : bscol));
1927     if (v & (T_R | FORWSLASH))
1928         draw_rect(dr, COORD(x+1)-1, COORD(y), 1, 1,
1929                   (v & ERR_T_R ? COL_ERROR : fscol));
1930     if (v & (C_TL | BACKSLASH))
1931         draw_rect(dr, COORD(x), COORD(y), 1, 1,
1932                   (v & ERR_C_TL ? COL_ERROR : bscol));
1933
1934     /*
1935      * And finally the clues at the corners.
1936      */
1937     if (x >= 0 && y >= 0)
1938         draw_clue(dr, ds, x, y, clues->clues[y*W+x], v & ERR_TL, -1, -1);
1939     if (x < w && y >= 0)
1940         draw_clue(dr, ds, x+1, y, clues->clues[y*W+(x+1)], v & ERR_TR, -1, -1);
1941     if (x >= 0 && y < h)
1942         draw_clue(dr, ds, x, y+1, clues->clues[(y+1)*W+x], v & ERR_BL, -1, -1);
1943     if (x < w && y < h)
1944         draw_clue(dr, ds, x+1, y+1, clues->clues[(y+1)*W+(x+1)], v & ERR_BR,
1945                   -1, -1);
1946
1947     unclip(dr);
1948     draw_update(dr, COORD(x), COORD(y), TILESIZE, TILESIZE);
1949 }
1950
1951 static void game_redraw(drawing *dr, game_drawstate *ds,
1952                         const game_state *oldstate, const game_state *state,
1953                         int dir, const game_ui *ui,
1954                         float animtime, float flashtime)
1955 {
1956     int w = state->p.w, h = state->p.h, W = w+1, H = h+1;
1957     int x, y;
1958     int flashing;
1959
1960     if (flashtime > 0)
1961         flashing = (int)(flashtime * 3 / FLASH_TIME) != 1;
1962     else
1963         flashing = FALSE;
1964
1965     if (!ds->started) {
1966         int ww, wh;
1967         game_compute_size(&state->p, TILESIZE, &ww, &wh);
1968         draw_rect(dr, 0, 0, ww, wh, COL_BACKGROUND);
1969         draw_update(dr, 0, 0, ww, wh);
1970         ds->started = TRUE;
1971     }
1972
1973     /*
1974      * Loop over the grid and work out where all the slashes are.
1975      * We need to do this because a slash in one square affects the
1976      * drawing of the next one along.
1977      */
1978     for (y = -1; y <= h; y++)
1979         for (x = -1; x <= w; x++) {
1980             if (x >= 0 && x < w && y >= 0 && y < h)
1981                 ds->todraw[(y+1)*(w+2)+(x+1)] = flashing ? FLASH : 0;
1982             else
1983                 ds->todraw[(y+1)*(w+2)+(x+1)] = 0;
1984         }
1985
1986     for (y = 0; y < h; y++) {
1987         for (x = 0; x < w; x++) {
1988             int err = state->errors[y*W+x] & ERR_SQUARE;
1989
1990             if (state->soln[y*w+x] < 0) {
1991                 ds->todraw[(y+1)*(w+2)+(x+1)] |= BACKSLASH;
1992                 ds->todraw[(y+2)*(w+2)+(x+1)] |= T_R;
1993                 ds->todraw[(y+1)*(w+2)+(x+2)] |= L_B;
1994                 ds->todraw[(y+2)*(w+2)+(x+2)] |= C_TL;
1995                 if (err) {
1996                     ds->todraw[(y+1)*(w+2)+(x+1)] |= ERRSLASH | 
1997                         ERR_T_L | ERR_L_T | ERR_C_TL;
1998                     ds->todraw[(y+2)*(w+2)+(x+1)] |= ERR_T_R;
1999                     ds->todraw[(y+1)*(w+2)+(x+2)] |= ERR_L_B;
2000                     ds->todraw[(y+2)*(w+2)+(x+2)] |= ERR_C_TL;
2001                 }
2002             } else if (state->soln[y*w+x] > 0) {
2003                 ds->todraw[(y+1)*(w+2)+(x+1)] |= FORWSLASH;
2004                 ds->todraw[(y+1)*(w+2)+(x+2)] |= L_T | C_TL;
2005                 ds->todraw[(y+2)*(w+2)+(x+1)] |= T_L | C_TL;
2006                 if (err) {
2007                     ds->todraw[(y+1)*(w+2)+(x+1)] |= ERRSLASH |
2008                         ERR_L_B | ERR_T_R;
2009                     ds->todraw[(y+1)*(w+2)+(x+2)] |= ERR_L_T | ERR_C_TL;
2010                     ds->todraw[(y+2)*(w+2)+(x+1)] |= ERR_T_L | ERR_C_TL;
2011                 }
2012             }
2013             if (ui->cur_visible && ui->cur_x == x && ui->cur_y == y)
2014                 ds->todraw[(y+1)*(w+2)+(x+1)] |= CURSOR;
2015         }
2016     }
2017
2018     for (y = 0; y < H; y++)
2019         for (x = 0; x < W; x++)
2020             if (state->errors[y*W+x] & ERR_VERTEX) {
2021                 ds->todraw[y*(w+2)+x] |= ERR_BR;
2022                 ds->todraw[y*(w+2)+(x+1)] |= ERR_BL;
2023                 ds->todraw[(y+1)*(w+2)+x] |= ERR_TR;
2024                 ds->todraw[(y+1)*(w+2)+(x+1)] |= ERR_TL;
2025             }
2026
2027     /*
2028      * Now go through and draw the grid squares.
2029      */
2030     for (y = -1; y <= h; y++) {
2031         for (x = -1; x <= w; x++) {
2032             if (ds->todraw[(y+1)*(w+2)+(x+1)] != ds->grid[(y+1)*(w+2)+(x+1)]) {
2033                 draw_tile(dr, ds, state->clues, x, y,
2034                           ds->todraw[(y+1)*(w+2)+(x+1)]);
2035                 ds->grid[(y+1)*(w+2)+(x+1)] = ds->todraw[(y+1)*(w+2)+(x+1)];
2036             }
2037         }
2038     }
2039 }
2040
2041 static float game_anim_length(const game_state *oldstate,
2042                               const game_state *newstate, int dir, game_ui *ui)
2043 {
2044     return 0.0F;
2045 }
2046
2047 static float game_flash_length(const game_state *oldstate,
2048                                const game_state *newstate, int dir, game_ui *ui)
2049 {
2050     if (!oldstate->completed && newstate->completed &&
2051         !oldstate->used_solve && !newstate->used_solve)
2052         return FLASH_TIME;
2053
2054     return 0.0F;
2055 }
2056
2057 static int game_status(const game_state *state)
2058 {
2059     return state->completed ? +1 : 0;
2060 }
2061
2062 static int game_timing_state(const game_state *state, game_ui *ui)
2063 {
2064     return TRUE;
2065 }
2066
2067 static void game_print_size(const game_params *params, float *x, float *y)
2068 {
2069     int pw, ph;
2070
2071     /*
2072      * I'll use 6mm squares by default.
2073      */
2074     game_compute_size(params, 600, &pw, &ph);
2075     *x = pw / 100.0F;
2076     *y = ph / 100.0F;
2077 }
2078
2079 static void game_print(drawing *dr, const game_state *state, int tilesize)
2080 {
2081     int w = state->p.w, h = state->p.h, W = w+1;
2082     int ink = print_mono_colour(dr, 0);
2083     int paper = print_mono_colour(dr, 1);
2084     int x, y;
2085
2086     /* Ick: fake up `ds->tilesize' for macro expansion purposes */
2087     game_drawstate ads, *ds = &ads;
2088     game_set_size(dr, ds, NULL, tilesize);
2089
2090     /*
2091      * Border.
2092      */
2093     print_line_width(dr, TILESIZE / 16);
2094     draw_rect_outline(dr, COORD(0), COORD(0), w*TILESIZE, h*TILESIZE, ink);
2095
2096     /*
2097      * Grid.
2098      */
2099     print_line_width(dr, TILESIZE / 24);
2100     for (x = 1; x < w; x++)
2101         draw_line(dr, COORD(x), COORD(0), COORD(x), COORD(h), ink);
2102     for (y = 1; y < h; y++)
2103         draw_line(dr, COORD(0), COORD(y), COORD(w), COORD(y), ink);
2104
2105     /*
2106      * Solution.
2107      */
2108     print_line_width(dr, TILESIZE / 12);
2109     for (y = 0; y < h; y++)
2110         for (x = 0; x < w; x++)
2111             if (state->soln[y*w+x]) {
2112                 int ly, ry;
2113                 /*
2114                  * To prevent nasty line-ending artefacts at
2115                  * corners, I'll do something slightly cunning
2116                  * here.
2117                  */
2118                 clip(dr, COORD(x), COORD(y), TILESIZE, TILESIZE);
2119                 if (state->soln[y*w+x] < 0)
2120                     ly = y-1, ry = y+2;
2121                 else
2122                     ry = y-1, ly = y+2;
2123                 draw_line(dr, COORD(x-1), COORD(ly), COORD(x+2), COORD(ry),
2124                           ink);
2125                 unclip(dr);
2126             }
2127
2128     /*
2129      * Clues.
2130      */
2131     print_line_width(dr, TILESIZE / 24);
2132     for (y = 0; y <= h; y++)
2133         for (x = 0; x <= w; x++)
2134             draw_clue(dr, ds, x, y, state->clues->clues[y*W+x],
2135                       FALSE, paper, ink);
2136 }
2137
2138 #ifdef COMBINED
2139 #define thegame slant
2140 #endif
2141
2142 const struct game thegame = {
2143     "Slant", "games.slant", "slant",
2144     default_params,
2145     game_fetch_preset, NULL,
2146     decode_params,
2147     encode_params,
2148     free_params,
2149     dup_params,
2150     TRUE, game_configure, custom_params,
2151     validate_params,
2152     new_game_desc,
2153     validate_desc,
2154     new_game,
2155     dup_game,
2156     free_game,
2157     TRUE, solve_game,
2158     TRUE, game_can_format_as_text_now, game_text_format,
2159     new_ui,
2160     free_ui,
2161     encode_ui,
2162     decode_ui,
2163     game_changed_state,
2164     interpret_move,
2165     execute_move,
2166     PREFERRED_TILESIZE, game_compute_size, game_set_size,
2167     game_colours,
2168     game_new_drawstate,
2169     game_free_drawstate,
2170     game_redraw,
2171     game_anim_length,
2172     game_flash_length,
2173     game_status,
2174     TRUE, FALSE, game_print_size, game_print,
2175     FALSE,                             /* wants_statusbar */
2176     FALSE, game_timing_state,
2177     0,                                 /* flags */
2178 };
2179
2180 #ifdef STANDALONE_SOLVER
2181
2182 #include <stdarg.h>
2183
2184 int main(int argc, char **argv)
2185 {
2186     game_params *p;
2187     game_state *s;
2188     char *id = NULL, *desc;
2189     const char *err;
2190     int grade = FALSE;
2191     int ret, diff, really_verbose = FALSE;
2192     struct solver_scratch *sc;
2193
2194     while (--argc > 0) {
2195         char *p = *++argv;
2196         if (!strcmp(p, "-v")) {
2197             really_verbose = TRUE;
2198         } else if (!strcmp(p, "-g")) {
2199             grade = TRUE;
2200         } else if (*p == '-') {
2201             fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
2202             return 1;
2203         } else {
2204             id = p;
2205         }
2206     }
2207
2208     if (!id) {
2209         fprintf(stderr, "usage: %s [-g | -v] <game_id>\n", argv[0]);
2210         return 1;
2211     }
2212
2213     desc = strchr(id, ':');
2214     if (!desc) {
2215         fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
2216         return 1;
2217     }
2218     *desc++ = '\0';
2219
2220     p = default_params();
2221     decode_params(p, id);
2222     err = validate_desc(p, desc);
2223     if (err) {
2224         fprintf(stderr, "%s: %s\n", argv[0], err);
2225         return 1;
2226     }
2227     s = new_game(NULL, p, desc);
2228
2229     sc = new_scratch(p->w, p->h);
2230
2231     /*
2232      * When solving an Easy puzzle, we don't want to bother the
2233      * user with Hard-level deductions. For this reason, we grade
2234      * the puzzle internally before doing anything else.
2235      */
2236     ret = -1;                          /* placate optimiser */
2237     for (diff = 0; diff < DIFFCOUNT; diff++) {
2238         ret = slant_solve(p->w, p->h, s->clues->clues,
2239                           s->soln, sc, diff);
2240         if (ret < 2)
2241             break;
2242     }
2243
2244     if (diff == DIFFCOUNT) {
2245         if (grade)
2246             printf("Difficulty rating: harder than Hard, or ambiguous\n");
2247         else
2248             printf("Unable to find a unique solution\n");
2249     } else {
2250         if (grade) {
2251             if (ret == 0)
2252                 printf("Difficulty rating: impossible (no solution exists)\n");
2253             else if (ret == 1)
2254                 printf("Difficulty rating: %s\n", slant_diffnames[diff]);
2255         } else {
2256             verbose = really_verbose;
2257             ret = slant_solve(p->w, p->h, s->clues->clues,
2258                               s->soln, sc, diff);
2259             if (ret == 0)
2260                 printf("Puzzle is inconsistent\n");
2261             else
2262                 fputs(game_text_format(s), stdout);
2263         }
2264     }
2265
2266     return 0;
2267 }
2268
2269 #endif
2270
2271 /* vim: set shiftwidth=4 tabstop=8: */