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