Add a STYLUS_BASED variant to magnets
[sgt-puzzles/ydirson.git] / tents.c
blobcfdcdc37786e2db8e4689fcc71a77ab07ad33019
1 /*
2 * tents.c: Puzzle involving placing tents next to trees subject to
3 * some confusing conditions.
4 *
5 * TODO:
7 * - it might be nice to make setter-provided tent/nontent clues
8 * inviolable?
9 * * on the other hand, this would introduce considerable extra
10 * complexity and size into the game state; also inviolable
11 * clues would have to be marked as such somehow, in an
12 * intrusive and annoying manner. Since they're never
13 * generated by _my_ generator, I'm currently more inclined
14 * not to bother.
16 * - more difficult levels at the top end?
17 * * for example, sometimes we can deduce that two BLANKs in
18 * the same row are each adjacent to the same unattached tree
19 * and to nothing else, implying that they can't both be
20 * tents; this enables us to rule out some extra combinations
21 * in the row-based deduction loop, and hence deduce more
22 * from the number in that row than we could otherwise do.
23 * * that by itself doesn't seem worth implementing a new
24 * difficulty level for, but if I can find a few more things
25 * like that then it might become worthwhile.
26 * * I wonder if there's a sensible heuristic for where to
27 * guess which would make a recursive solver viable?
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <assert.h>
34 #include <ctype.h>
35 #include <math.h>
37 #include "puzzles.h"
38 #include "maxflow.h"
41 * Design discussion
42 * -----------------
44 * The rules of this puzzle as available on the WWW are poorly
45 * specified. The bits about tents having to be orthogonally
46 * adjacent to trees, tents not being even diagonally adjacent to
47 * one another, and the number of tents in each row and column
48 * being given are simple enough; the difficult bit is the
49 * tent-to-tree matching.
51 * Some sources use simplistic wordings such as `each tree is
52 * exactly connected to only one tent', which is extremely unclear:
53 * it's easy to read erroneously as `each tree is _orthogonally
54 * adjacent_ to exactly one tent', which is definitely incorrect.
55 * Even the most coherent sources I've found don't do a much better
56 * job of stating the rule.
58 * A more precise statement of the rule is that it must be possible
59 * to find a bijection f between tents and trees such that each
60 * tree T is orthogonally adjacent to the tent f(T), but that a
61 * tent is permitted to be adjacent to other trees in addition to
62 * its own. This slightly non-obvious criterion is what gives this
63 * puzzle most of its subtlety.
65 * However, there's a particularly subtle ambiguity left over. Is
66 * the bijection between tents and trees required to be _unique_?
67 * In other words, is that bijection conceptually something the
68 * player should be able to exhibit as part of the solution (even
69 * if they aren't actually required to do so)? Or is it sufficient
70 * to have a unique _placement_ of the tents which gives rise to at
71 * least one suitable bijection?
73 * The puzzle shown to the right of this .T. 2 *T* 2
74 * paragraph illustrates the problem. There T.T 0 -> T-T 0
75 * are two distinct bijections available. .T. 2 *T* 2
76 * The answer to the above question will
77 * determine whether it's a valid puzzle. 202 202
79 * This is an important question, because it affects both the
80 * player and the generator. Eventually I found all the instances
81 * of this puzzle I could Google up, solved them all by hand, and
82 * verified that in all cases the tree/tent matching was uniquely
83 * determined given the tree and tent positions. Therefore, the
84 * puzzle as implemented in this source file takes the following
85 * policy:
87 * - When checking a user-supplied solution for correctness, only
88 * verify that there exists _at least_ one matching.
89 * - When generating a puzzle, enforce that there must be
90 * _exactly_ one.
92 * Algorithmic implications
93 * ------------------------
95 * Another way of phrasing the tree/tent matching criterion is to
96 * say that the bipartite adjacency graph between trees and tents
97 * has a perfect matching. That is, if you construct a graph which
98 * has a vertex per tree and a vertex per tent, and an edge between
99 * any tree and tent which are orthogonally adjacent, it is
100 * possible to find a set of N edges of that graph (where N is the
101 * number of trees and also the number of tents) which between them
102 * connect every tree to every tent.
104 * The most efficient known algorithms for finding such a matching
105 * given a graph, as far as I'm aware, are the Munkres assignment
106 * algorithm (also known as the Hungarian algorithm) and the
107 * Ford-Fulkerson algorithm (for finding optimal flows in
108 * networks). Each of these takes O(N^3) running time; so we're
109 * talking O(N^3) time to verify any candidate solution to this
110 * puzzle. That's just about OK if you're doing it once per mouse
111 * click (and in fact not even that, since the sensible thing to do
112 * is check all the _other_ puzzle criteria and only wade into this
113 * quagmire if none are violated); but if the solver had to keep
114 * doing N^3 work internally, then it would probably end up with
115 * more like N^5 or N^6 running time, and grid generation would
116 * become very clunky.
118 * Fortunately, I've been able to prove a very useful property of
119 * _unique_ perfect matchings, by adapting the proof of Hall's
120 * Marriage Theorem. For those unaware of Hall's Theorem, I'll
121 * recap it and its proof: it states that a bipartite graph
122 * contains a perfect matching iff every set of vertices on the
123 * left side of the graph have a neighbourhood _at least_ as big on
124 * the right.
126 * This condition is obviously satisfied if a perfect matching does
127 * exist; each left-side node has a distinct right-side node which
128 * is the one assigned to it by the matching, and thus any set of n
129 * left vertices must have a combined neighbourhood containing at
130 * least the n corresponding right vertices, and possibly others
131 * too. Alternatively, imagine if you had (say) three left-side
132 * nodes all of which were connected to only two right-side nodes
133 * between them: any perfect matching would have to assign one of
134 * those two right nodes to each of the three left nodes, and still
135 * give the three left nodes a different right node each. This is
136 * of course impossible.
138 * To prove the converse (that if every subset of left vertices
139 * satisfies the Hall condition then a perfect matching exists),
140 * consider trying to find a proper subset of the left vertices
141 * which _exactly_ satisfies the Hall condition: that is, its right
142 * neighbourhood is precisely the same size as it. If we can find
143 * such a subset, then we can split the bipartite graph into two
144 * smaller ones: one consisting of the left subset and its right
145 * neighbourhood, the other consisting of everything else. Edges
146 * from the left side of the former graph to the right side of the
147 * latter do not exist, by construction; edges from the right side
148 * of the former to the left of the latter cannot be part of any
149 * perfect matching because otherwise the left subset would not be
150 * left with enough distinct right vertices to connect to (this is
151 * exactly the same deduction used in Solo's set analysis). You can
152 * then prove (left as an exercise) that both these smaller graphs
153 * still satisfy the Hall condition, and therefore the proof will
154 * follow by induction.
156 * There's one other possibility, which is the case where _no_
157 * proper subset of the left vertices has a right neighbourhood of
158 * exactly the same size. That is, every left subset has a strictly
159 * _larger_ right neighbourhood. In this situation, we can simply
160 * remove an _arbitrary_ edge from the graph. This cannot reduce
161 * the size of any left subset's right neighbourhood by more than
162 * one, so if all neighbourhoods were strictly bigger than they
163 * needed to be initially, they must now still be _at least as big_
164 * as they need to be. So we can keep throwing out arbitrary edges
165 * until we find a set which exactly satisfies the Hall condition,
166 * and then proceed as above. []
168 * That's Hall's theorem. I now build on this by examining the
169 * circumstances in which a bipartite graph can have a _unique_
170 * perfect matching. It is clear that in the second case, where no
171 * left subset exactly satisfies the Hall condition and so we can
172 * remove an arbitrary edge, there cannot be a unique perfect
173 * matching: given one perfect matching, we choose our arbitrary
174 * removed edge to be one of those contained in it, and then we can
175 * still find a perfect matching in the remaining graph, which will
176 * be a distinct perfect matching in the original.
178 * So it is a necessary condition for a unique perfect matching
179 * that there must be at least one proper left subset which
180 * _exactly_ satisfies the Hall condition. But now consider the
181 * smaller graph constructed by taking that left subset and its
182 * neighbourhood: if the graph as a whole had a unique perfect
183 * matching, then so must this smaller one, which means we can find
184 * a proper left subset _again_, and so on. Repeating this process
185 * must eventually reduce us to a graph with only one left-side
186 * vertex (so there are no proper subsets at all); this vertex must
187 * be connected to only one right-side vertex, and hence must be so
188 * in the original graph as well (by construction). So we can
189 * discard this vertex pair from the graph, and any other edges
190 * that involved it (which will by construction be from other left
191 * vertices only), and the resulting smaller graph still has a
192 * unique perfect matching which means we can do the same thing
193 * again.
195 * In other words, given any bipartite graph with a unique perfect
196 * matching, we can find that matching by the following extremely
197 * simple algorithm:
199 * - Find a left-side vertex which is only connected to one
200 * right-side vertex.
201 * - Assign those vertices to one another, and therefore discard
202 * any other edges connecting to that right vertex.
203 * - Repeat until all vertices have been matched.
205 * This algorithm can be run in O(V+E) time (where V is the number
206 * of vertices and E is the number of edges in the graph), and the
207 * only way it can fail is if there is not a unique perfect
208 * matching (either because there is no matching at all, or because
209 * it isn't unique; but it can't distinguish those cases).
211 * Thus, the internal solver in this source file can be confident
212 * that if the tree/tent matching is uniquely determined by the
213 * tree and tent positions, it can find it using only this kind of
214 * obvious and simple operation: assign a tree to a tent if it
215 * cannot possibly belong to any other tent, and vice versa. If the
216 * solver were _only_ trying to determine the matching, even that
217 * `vice versa' wouldn't be required; but it can come in handy when
218 * not all the tents have been placed yet. I can therefore be
219 * reasonably confident that as long as my solver doesn't need to
220 * cope with grids that have a non-unique matching, it will also
221 * not need to do anything complicated like set analysis between
222 * trees and tents.
226 * In standalone solver mode, `verbose' is a variable which can be
227 * set by command-line option; in debugging mode it's simply always
228 * true.
230 #if defined STANDALONE_SOLVER
231 #define SOLVER_DIAGNOSTICS
232 int verbose = FALSE;
233 #elif defined SOLVER_DIAGNOSTICS
234 #define verbose TRUE
235 #endif
238 * Difficulty levels. I do some macro ickery here to ensure that my
239 * enum and the various forms of my name list always match up.
241 #define DIFFLIST(A) \
242 A(EASY,Easy,e) \
243 A(TRICKY,Tricky,t)
244 #define ENUM(upper,title,lower) DIFF_ ## upper,
245 #define TITLE(upper,title,lower) #title,
246 #define ENCODE(upper,title,lower) #lower
247 #define CONFIG(upper,title,lower) ":" #title
248 enum { DIFFLIST(ENUM) DIFFCOUNT };
249 static char const *const tents_diffnames[] = { DIFFLIST(TITLE) };
250 static char const tents_diffchars[] = DIFFLIST(ENCODE);
251 #define DIFFCONFIG DIFFLIST(CONFIG)
253 enum {
254 COL_BACKGROUND,
255 COL_GRID,
256 COL_GRASS,
257 COL_TREETRUNK,
258 COL_TREELEAF,
259 COL_TENT,
260 COL_ERROR,
261 COL_ERRTEXT,
262 COL_ERRTRUNK,
263 NCOLOURS
266 enum { BLANK, TREE, TENT, NONTENT, MAGIC };
268 struct game_params {
269 int w, h;
270 int diff;
273 struct numbers {
274 int refcount;
275 int *numbers;
278 struct game_state {
279 game_params p;
280 char *grid;
281 struct numbers *numbers;
282 int completed, used_solve;
285 static game_params *default_params(void)
287 game_params *ret = snew(game_params);
289 ret->w = ret->h = 8;
290 ret->diff = DIFF_EASY;
292 return ret;
295 static const struct game_params tents_presets[] = {
296 {8, 8, DIFF_EASY},
297 {8, 8, DIFF_TRICKY},
298 {10, 10, DIFF_EASY},
299 {10, 10, DIFF_TRICKY},
300 {15, 15, DIFF_EASY},
301 {15, 15, DIFF_TRICKY},
304 static int game_fetch_preset(int i, char **name, game_params **params)
306 game_params *ret;
307 char str[80];
309 if (i < 0 || i >= lenof(tents_presets))
310 return FALSE;
312 ret = snew(game_params);
313 *ret = tents_presets[i];
315 sprintf(str, "%dx%d %s", ret->w, ret->h, tents_diffnames[ret->diff]);
317 *name = dupstr(str);
318 *params = ret;
319 return TRUE;
322 static void free_params(game_params *params)
324 sfree(params);
327 static game_params *dup_params(game_params *params)
329 game_params *ret = snew(game_params);
330 *ret = *params; /* structure copy */
331 return ret;
334 static void decode_params(game_params *params, char const *string)
336 params->w = params->h = atoi(string);
337 while (*string && isdigit((unsigned char)*string)) string++;
338 if (*string == 'x') {
339 string++;
340 params->h = atoi(string);
341 while (*string && isdigit((unsigned char)*string)) string++;
343 if (*string == 'd') {
344 int i;
345 string++;
346 for (i = 0; i < DIFFCOUNT; i++)
347 if (*string == tents_diffchars[i])
348 params->diff = i;
349 if (*string) string++;
353 static char *encode_params(game_params *params, int full)
355 char buf[120];
357 sprintf(buf, "%dx%d", params->w, params->h);
358 if (full)
359 sprintf(buf + strlen(buf), "d%c",
360 tents_diffchars[params->diff]);
361 return dupstr(buf);
364 static config_item *game_configure(game_params *params)
366 config_item *ret;
367 char buf[80];
369 ret = snewn(4, config_item);
371 ret[0].name = "Width";
372 ret[0].type = C_STRING;
373 sprintf(buf, "%d", params->w);
374 ret[0].sval = dupstr(buf);
375 ret[0].ival = 0;
377 ret[1].name = "Height";
378 ret[1].type = C_STRING;
379 sprintf(buf, "%d", params->h);
380 ret[1].sval = dupstr(buf);
381 ret[1].ival = 0;
383 ret[2].name = "Difficulty";
384 ret[2].type = C_CHOICES;
385 ret[2].sval = DIFFCONFIG;
386 ret[2].ival = params->diff;
388 ret[3].name = NULL;
389 ret[3].type = C_END;
390 ret[3].sval = NULL;
391 ret[3].ival = 0;
393 return ret;
396 static game_params *custom_params(config_item *cfg)
398 game_params *ret = snew(game_params);
400 ret->w = atoi(cfg[0].sval);
401 ret->h = atoi(cfg[1].sval);
402 ret->diff = cfg[2].ival;
404 return ret;
407 static char *validate_params(game_params *params, int full)
410 * Generating anything under 4x4 runs into trouble of one kind
411 * or another.
413 if (params->w < 4 || params->h < 4)
414 return "Width and height must both be at least four";
415 return NULL;
419 * Scratch space for solver.
421 enum { N, U, L, R, D, MAXDIR }; /* link directions */
422 #define dx(d) ( ((d)==R) - ((d)==L) )
423 #define dy(d) ( ((d)==D) - ((d)==U) )
424 #define F(d) ( U + D - (d) )
425 struct solver_scratch {
426 char *links; /* mapping between trees and tents */
427 int *locs;
428 char *place, *mrows, *trows;
431 static struct solver_scratch *new_scratch(int w, int h)
433 struct solver_scratch *ret = snew(struct solver_scratch);
435 ret->links = snewn(w*h, char);
436 ret->locs = snewn(max(w, h), int);
437 ret->place = snewn(max(w, h), char);
438 ret->mrows = snewn(3 * max(w, h), char);
439 ret->trows = snewn(3 * max(w, h), char);
441 return ret;
444 static void free_scratch(struct solver_scratch *sc)
446 sfree(sc->trows);
447 sfree(sc->mrows);
448 sfree(sc->place);
449 sfree(sc->locs);
450 sfree(sc->links);
451 sfree(sc);
455 * Solver. Returns 0 for impossibility, 1 for success, 2 for
456 * ambiguity or failure to converge.
458 static int tents_solve(int w, int h, const char *grid, int *numbers,
459 char *soln, struct solver_scratch *sc, int diff)
461 int x, y, d, i, j;
462 char *mrow, *trow, *trow1, *trow2;
465 * Set up solver data.
467 memset(sc->links, N, w*h);
470 * Set up solution array.
472 memcpy(soln, grid, w*h);
475 * Main solver loop.
477 while (1) {
478 int done_something = FALSE;
481 * Any tent which has only one unattached tree adjacent to
482 * it can be tied to that tree.
484 for (y = 0; y < h; y++)
485 for (x = 0; x < w; x++)
486 if (soln[y*w+x] == TENT && !sc->links[y*w+x]) {
487 int linkd = 0;
489 for (d = 1; d < MAXDIR; d++) {
490 int x2 = x + dx(d), y2 = y + dy(d);
491 if (x2 >= 0 && x2 < w && y2 >= 0 && y2 < h &&
492 soln[y2*w+x2] == TREE &&
493 !sc->links[y2*w+x2]) {
494 if (linkd)
495 break; /* found more than one */
496 else
497 linkd = d;
501 if (d == MAXDIR && linkd == 0) {
502 #ifdef SOLVER_DIAGNOSTICS
503 if (verbose)
504 printf("tent at %d,%d cannot link to anything\n",
505 x, y);
506 #endif
507 return 0; /* no solution exists */
508 } else if (d == MAXDIR) {
509 int x2 = x + dx(linkd), y2 = y + dy(linkd);
511 #ifdef SOLVER_DIAGNOSTICS
512 if (verbose)
513 printf("tent at %d,%d can only link to tree at"
514 " %d,%d\n", x, y, x2, y2);
515 #endif
517 sc->links[y*w+x] = linkd;
518 sc->links[y2*w+x2] = F(linkd);
519 done_something = TRUE;
523 if (done_something)
524 continue;
525 if (diff < 0)
526 break; /* don't do anything else! */
529 * Mark a blank square as NONTENT if it is not orthogonally
530 * adjacent to any unmatched tree.
532 for (y = 0; y < h; y++)
533 for (x = 0; x < w; x++)
534 if (soln[y*w+x] == BLANK) {
535 int can_be_tent = FALSE;
537 for (d = 1; d < MAXDIR; d++) {
538 int x2 = x + dx(d), y2 = y + dy(d);
539 if (x2 >= 0 && x2 < w && y2 >= 0 && y2 < h &&
540 soln[y2*w+x2] == TREE &&
541 !sc->links[y2*w+x2])
542 can_be_tent = TRUE;
545 if (!can_be_tent) {
546 #ifdef SOLVER_DIAGNOSTICS
547 if (verbose)
548 printf("%d,%d cannot be a tent (no adjacent"
549 " unmatched tree)\n", x, y);
550 #endif
551 soln[y*w+x] = NONTENT;
552 done_something = TRUE;
556 if (done_something)
557 continue;
560 * Mark a blank square as NONTENT if it is (perhaps
561 * diagonally) adjacent to any other tent.
563 for (y = 0; y < h; y++)
564 for (x = 0; x < w; x++)
565 if (soln[y*w+x] == BLANK) {
566 int dx, dy, imposs = FALSE;
568 for (dy = -1; dy <= +1; dy++)
569 for (dx = -1; dx <= +1; dx++)
570 if (dy || dx) {
571 int x2 = x + dx, y2 = y + dy;
572 if (x2 >= 0 && x2 < w && y2 >= 0 && y2 < h &&
573 soln[y2*w+x2] == TENT)
574 imposs = TRUE;
577 if (imposs) {
578 #ifdef SOLVER_DIAGNOSTICS
579 if (verbose)
580 printf("%d,%d cannot be a tent (adjacent tent)\n",
581 x, y);
582 #endif
583 soln[y*w+x] = NONTENT;
584 done_something = TRUE;
588 if (done_something)
589 continue;
592 * Any tree which has exactly one {unattached tent, BLANK}
593 * adjacent to it must have its tent in that square.
595 for (y = 0; y < h; y++)
596 for (x = 0; x < w; x++)
597 if (soln[y*w+x] == TREE && !sc->links[y*w+x]) {
598 int linkd = 0, linkd2 = 0, nd = 0;
600 for (d = 1; d < MAXDIR; d++) {
601 int x2 = x + dx(d), y2 = y + dy(d);
602 if (!(x2 >= 0 && x2 < w && y2 >= 0 && y2 < h))
603 continue;
604 if (soln[y2*w+x2] == BLANK ||
605 (soln[y2*w+x2] == TENT && !sc->links[y2*w+x2])) {
606 if (linkd)
607 linkd2 = d;
608 else
609 linkd = d;
610 nd++;
614 if (nd == 0) {
615 #ifdef SOLVER_DIAGNOSTICS
616 if (verbose)
617 printf("tree at %d,%d cannot link to anything\n",
618 x, y);
619 #endif
620 return 0; /* no solution exists */
621 } else if (nd == 1) {
622 int x2 = x + dx(linkd), y2 = y + dy(linkd);
624 #ifdef SOLVER_DIAGNOSTICS
625 if (verbose)
626 printf("tree at %d,%d can only link to tent at"
627 " %d,%d\n", x, y, x2, y2);
628 #endif
629 soln[y2*w+x2] = TENT;
630 sc->links[y*w+x] = linkd;
631 sc->links[y2*w+x2] = F(linkd);
632 done_something = TRUE;
633 } else if (nd == 2 && (!dx(linkd) != !dx(linkd2)) &&
634 diff >= DIFF_TRICKY) {
636 * If there are two possible places where
637 * this tree's tent can go, and they are
638 * diagonally separated rather than being
639 * on opposite sides of the tree, then the
640 * square (other than the tree square)
641 * which is adjacent to both of them must
642 * be a non-tent.
644 int x2 = x + dx(linkd) + dx(linkd2);
645 int y2 = y + dy(linkd) + dy(linkd2);
646 assert(x2 >= 0 && x2 < w && y2 >= 0 && y2 < h);
647 if (soln[y2*w+x2] == BLANK) {
648 #ifdef SOLVER_DIAGNOSTICS
649 if (verbose)
650 printf("possible tent locations for tree at"
651 " %d,%d rule out tent at %d,%d\n",
652 x, y, x2, y2);
653 #endif
654 soln[y2*w+x2] = NONTENT;
655 done_something = TRUE;
660 if (done_something)
661 continue;
664 * If localised deductions about the trees and tents
665 * themselves haven't helped us, it's time to resort to the
666 * numbers round the grid edge. For each row and column, we
667 * go through all possible combinations of locations for
668 * the unplaced tents, rule out any which have adjacent
669 * tents, and spot any square which is given the same state
670 * by all remaining combinations.
672 for (i = 0; i < w+h; i++) {
673 int start, step, len, start1, start2, n, k;
675 if (i < w) {
677 * This is the number for a column.
679 start = i;
680 step = w;
681 len = h;
682 if (i > 0)
683 start1 = start - 1;
684 else
685 start1 = -1;
686 if (i+1 < w)
687 start2 = start + 1;
688 else
689 start2 = -1;
690 } else {
692 * This is the number for a row.
694 start = (i-w)*w;
695 step = 1;
696 len = w;
697 if (i > w)
698 start1 = start - w;
699 else
700 start1 = -1;
701 if (i+1 < w+h)
702 start2 = start + w;
703 else
704 start2 = -1;
707 if (diff < DIFF_TRICKY) {
709 * In Easy mode, we don't look at the effect of one
710 * row on the next (i.e. ruling out a square if all
711 * possibilities for an adjacent row place a tent
712 * next to it).
714 start1 = start2 = -1;
717 k = numbers[i];
720 * Count and store the locations of the free squares,
721 * and also count the number of tents already placed.
723 n = 0;
724 for (j = 0; j < len; j++) {
725 if (soln[start+j*step] == TENT)
726 k--; /* one fewer tent to place */
727 else if (soln[start+j*step] == BLANK)
728 sc->locs[n++] = j;
731 if (n == 0)
732 continue; /* nothing left to do here */
735 * Now we know we're placing k tents in n squares. Set
736 * up the first possibility.
738 for (j = 0; j < n; j++)
739 sc->place[j] = (j < k ? TENT : NONTENT);
742 * We're aiming to find squares in this row which are
743 * invariant over all valid possibilities. Thus, we
744 * maintain the current state of that invariance. We
745 * start everything off at MAGIC to indicate that it
746 * hasn't been set up yet.
748 mrow = sc->mrows;
749 trow = sc->trows;
750 trow1 = sc->trows + len;
751 trow2 = sc->trows + 2*len;
752 memset(mrow, MAGIC, 3*len);
755 * And iterate over all possibilities.
757 while (1) {
758 int p, valid;
761 * See if this possibility is valid. The only way
762 * it can fail to be valid is if it contains two
763 * adjacent tents. (Other forms of invalidity, such
764 * as containing a tent adjacent to one already
765 * placed, will have been dealt with already by
766 * other parts of the solver.)
768 valid = TRUE;
769 for (j = 0; j+1 < n; j++)
770 if (sc->place[j] == TENT &&
771 sc->place[j+1] == TENT &&
772 sc->locs[j+1] == sc->locs[j]+1) {
773 valid = FALSE;
774 break;
777 if (valid) {
779 * Merge this valid combination into mrow.
781 memset(trow, MAGIC, len);
782 memset(trow+len, BLANK, 2*len);
783 for (j = 0; j < n; j++) {
784 trow[sc->locs[j]] = sc->place[j];
785 if (sc->place[j] == TENT) {
786 int jj;
787 for (jj = sc->locs[j]-1; jj <= sc->locs[j]+1; jj++)
788 if (jj >= 0 && jj < len)
789 trow1[jj] = trow2[jj] = NONTENT;
793 for (j = 0; j < 3*len; j++) {
794 if (trow[j] == MAGIC)
795 continue;
796 if (mrow[j] == MAGIC || mrow[j] == trow[j]) {
798 * Either this is the first valid
799 * placement we've found at all, or
800 * this square's contents are
801 * consistent with every previous valid
802 * combination.
804 mrow[j] = trow[j];
805 } else {
807 * This square's contents fail to match
808 * what they were in a different
809 * combination, so we cannot deduce
810 * anything about this square.
812 mrow[j] = BLANK;
818 * Find the next combination of k choices from n.
819 * We do this by finding the rightmost tent which
820 * can be moved one place right, doing so, and
821 * shunting all tents to the right of that as far
822 * left as they can go.
824 p = 0;
825 for (j = n-1; j > 0; j--) {
826 if (sc->place[j] == TENT)
827 p++;
828 if (sc->place[j] == NONTENT && sc->place[j-1] == TENT) {
829 sc->place[j-1] = NONTENT;
830 sc->place[j] = TENT;
831 while (p--)
832 sc->place[++j] = TENT;
833 while (++j < n)
834 sc->place[j] = NONTENT;
835 break;
838 if (j <= 0)
839 break; /* we've finished */
843 * It's just possible that _no_ placement was valid, in
844 * which case we have an internally inconsistent
845 * puzzle.
847 if (mrow[sc->locs[0]] == MAGIC)
848 return 0; /* inconsistent */
851 * Now go through mrow and see if there's anything
852 * we've deduced which wasn't already mentioned in soln.
854 for (j = 0; j < len; j++) {
855 int whichrow;
857 for (whichrow = 0; whichrow < 3; whichrow++) {
858 char *mthis = mrow + whichrow * len;
859 int tstart = (whichrow == 0 ? start :
860 whichrow == 1 ? start1 : start2);
861 if (tstart >= 0 &&
862 mthis[j] != MAGIC && mthis[j] != BLANK &&
863 soln[tstart+j*step] == BLANK) {
864 int pos = tstart+j*step;
866 #ifdef SOLVER_DIAGNOSTICS
867 if (verbose)
868 printf("%s %d forces %s at %d,%d\n",
869 step==1 ? "row" : "column",
870 step==1 ? start/w : start,
871 mthis[j] == TENT ? "tent" : "non-tent",
872 pos % w, pos / w);
873 #endif
874 soln[pos] = mthis[j];
875 done_something = TRUE;
881 if (done_something)
882 continue;
884 if (!done_something)
885 break;
889 * The solver has nothing further it can do. Return 1 if both
890 * soln and sc->links are completely filled in, or 2 otherwise.
892 for (y = 0; y < h; y++)
893 for (x = 0; x < w; x++) {
894 if (soln[y*w+x] == BLANK)
895 return 2;
896 if (soln[y*w+x] != NONTENT && sc->links[y*w+x] == 0)
897 return 2;
900 return 1;
903 static char *new_game_desc(game_params *params, random_state *rs,
904 char **aux, int interactive)
906 int w = params->w, h = params->h;
907 int ntrees = w * h / 5;
908 char *grid = snewn(w*h, char);
909 char *puzzle = snewn(w*h, char);
910 int *numbers = snewn(w+h, int);
911 char *soln = snewn(w*h, char);
912 int *temp = snewn(2*w*h, int);
913 int maxedges = ntrees*4 + w*h;
914 int *edges = snewn(2*maxedges, int);
915 int *capacity = snewn(maxedges, int);
916 int *flow = snewn(maxedges, int);
917 struct solver_scratch *sc = new_scratch(w, h);
918 char *ret, *p;
919 int i, j, nedges;
922 * Since this puzzle has many global deductions and doesn't
923 * permit limited clue sets, generating grids for this puzzle
924 * is hard enough that I see no better option than to simply
925 * generate a solution and see if it's unique and has the
926 * required difficulty. This turns out to be computationally
927 * plausible as well.
929 * We chose our tree count (hence also tent count) by dividing
930 * the total grid area by five above. Why five? Well, w*h/4 is
931 * the maximum number of tents you can _possibly_ fit into the
932 * grid without violating the separation criterion, and to
933 * achieve that you are constrained to a very small set of
934 * possible layouts (the obvious one with a tent at every
935 * (even,even) coordinate, and trivial variations thereon). So
936 * if we reduce the tent count a bit more, we enable more
937 * random-looking placement; 5 turns out to be a plausible
938 * figure which yields sensible puzzles. Increasing the tent
939 * count would give puzzles whose solutions were too regimented
940 * and could be solved by the use of that knowledge (and would
941 * also take longer to find a viable placement); decreasing it
942 * would make the grids emptier and more boring.
944 * Actually generating a grid is a matter of first placing the
945 * tents, and then placing the trees by the use of maxflow
946 * (finding a distinct square adjacent to every tent). We do it
947 * this way round because otherwise satisfying the tent
948 * separation condition would become onerous: most randomly
949 * chosen tent layouts do not satisfy this condition, so we'd
950 * have gone to a lot of work before finding that a candidate
951 * layout was unusable. Instead, we place the tents first and
952 * ensure they meet the separation criterion _before_ doing
953 * lots of computation; this works much better.
955 * The maxflow algorithm is not randomised, so employed naively
956 * it would give rise to grids with clear structure and
957 * directional bias. Hence, I assign the network nodes as seen
958 * by maxflow to be a _random_ permutation of the squares of
959 * the grid, so that any bias shown by maxflow towards
960 * low-numbered nodes is turned into a random bias.
962 * This generation strategy can fail at many points, including
963 * as early as tent placement (if you get a bad random order in
964 * which to greedily try the grid squares, you won't even
965 * manage to find enough mutually non-adjacent squares to put
966 * the tents in). Then it can fail if maxflow doesn't manage to
967 * find a good enough matching (i.e. the tent placements don't
968 * admit any adequate tree placements); and finally it can fail
969 * if the solver finds that the problem has the wrong
970 * difficulty (including being actually non-unique). All of
971 * these, however, are insufficiently frequent to cause
972 * trouble.
975 if (params->diff > DIFF_EASY && params->w <= 4 && params->h <= 4)
976 params->diff = DIFF_EASY; /* downgrade to prevent tight loop */
978 while (1) {
980 * Arrange the grid squares into a random order.
982 for (i = 0; i < w*h; i++)
983 temp[i] = i;
984 shuffle(temp, w*h, sizeof(*temp), rs);
987 * The first `ntrees' entries in temp which we can get
988 * without making two tents adjacent will be the tent
989 * locations.
991 memset(grid, BLANK, w*h);
992 j = ntrees;
993 for (i = 0; i < w*h && j > 0; i++) {
994 int x = temp[i] % w, y = temp[i] / w;
995 int dy, dx, ok = TRUE;
997 for (dy = -1; dy <= +1; dy++)
998 for (dx = -1; dx <= +1; dx++)
999 if (x+dx >= 0 && x+dx < w &&
1000 y+dy >= 0 && y+dy < h &&
1001 grid[(y+dy)*w+(x+dx)] == TENT)
1002 ok = FALSE;
1004 if (ok) {
1005 grid[temp[i]] = TENT;
1006 j--;
1009 if (j > 0)
1010 continue; /* couldn't place all the tents */
1013 * Now we build up the list of graph edges.
1015 nedges = 0;
1016 for (i = 0; i < w*h; i++) {
1017 if (grid[temp[i]] == TENT) {
1018 for (j = 0; j < w*h; j++) {
1019 if (grid[temp[j]] != TENT) {
1020 int xi = temp[i] % w, yi = temp[i] / w;
1021 int xj = temp[j] % w, yj = temp[j] / w;
1022 if (abs(xi-xj) + abs(yi-yj) == 1) {
1023 edges[nedges*2] = i;
1024 edges[nedges*2+1] = j;
1025 capacity[nedges] = 1;
1026 nedges++;
1030 } else {
1032 * Special node w*h is the sink node; any non-tent node
1033 * has an edge going to it.
1035 edges[nedges*2] = i;
1036 edges[nedges*2+1] = w*h;
1037 capacity[nedges] = 1;
1038 nedges++;
1043 * Special node w*h+1 is the source node, with an edge going to
1044 * every tent.
1046 for (i = 0; i < w*h; i++) {
1047 if (grid[temp[i]] == TENT) {
1048 edges[nedges*2] = w*h+1;
1049 edges[nedges*2+1] = i;
1050 capacity[nedges] = 1;
1051 nedges++;
1055 assert(nedges <= maxedges);
1058 * Now we're ready to call the maxflow algorithm to place the
1059 * trees.
1061 j = maxflow(w*h+2, w*h+1, w*h, nedges, edges, capacity, flow, NULL);
1063 if (j < ntrees)
1064 continue; /* couldn't place all the tents */
1067 * We've placed the trees. Now we need to work out _where_
1068 * we've placed them, which is a matter of reading back out
1069 * from the `flow' array.
1071 for (i = 0; i < nedges; i++) {
1072 if (edges[2*i] < w*h && edges[2*i+1] < w*h && flow[i] > 0)
1073 grid[temp[edges[2*i+1]]] = TREE;
1077 * I think it looks ugly if there isn't at least one of
1078 * _something_ (tent or tree) in each row and each column
1079 * of the grid. This doesn't give any information away
1080 * since a completely empty row/column is instantly obvious
1081 * from the clues (it has no trees and a zero).
1083 for (i = 0; i < w; i++) {
1084 for (j = 0; j < h; j++) {
1085 if (grid[j*w+i] != BLANK)
1086 break; /* found something in this column */
1088 if (j == h)
1089 break; /* found empty column */
1091 if (i < w)
1092 continue; /* a column was empty */
1094 for (j = 0; j < h; j++) {
1095 for (i = 0; i < w; i++) {
1096 if (grid[j*w+i] != BLANK)
1097 break; /* found something in this row */
1099 if (i == w)
1100 break; /* found empty row */
1102 if (j < h)
1103 continue; /* a row was empty */
1106 * Now set up the numbers round the edge.
1108 for (i = 0; i < w; i++) {
1109 int n = 0;
1110 for (j = 0; j < h; j++)
1111 if (grid[j*w+i] == TENT)
1112 n++;
1113 numbers[i] = n;
1115 for (i = 0; i < h; i++) {
1116 int n = 0;
1117 for (j = 0; j < w; j++)
1118 if (grid[i*w+j] == TENT)
1119 n++;
1120 numbers[w+i] = n;
1124 * And now actually solve the puzzle, to see whether it's
1125 * unique and has the required difficulty.
1127 for (i = 0; i < w*h; i++)
1128 puzzle[i] = grid[i] == TREE ? TREE : BLANK;
1129 i = tents_solve(w, h, puzzle, numbers, soln, sc, params->diff-1);
1130 j = tents_solve(w, h, puzzle, numbers, soln, sc, params->diff);
1133 * We expect solving with difficulty params->diff to have
1134 * succeeded (otherwise the problem is too hard), and
1135 * solving with diff-1 to have failed (otherwise it's too
1136 * easy).
1138 if (i == 2 && j == 1)
1139 break;
1143 * That's it. Encode as a game ID.
1145 ret = snewn((w+h)*40 + ntrees + (w*h)/26 + 1, char);
1146 p = ret;
1147 j = 0;
1148 for (i = 0; i <= w*h; i++) {
1149 int c = (i < w*h ? grid[i] == TREE : 1);
1150 if (c) {
1151 *p++ = (j == 0 ? '_' : j-1 + 'a');
1152 j = 0;
1153 } else {
1154 j++;
1155 while (j > 25) {
1156 *p++ = 'z';
1157 j -= 25;
1161 for (i = 0; i < w+h; i++)
1162 p += sprintf(p, ",%d", numbers[i]);
1163 *p++ = '\0';
1164 ret = sresize(ret, p - ret, char);
1167 * And encode the solution as an aux_info.
1169 *aux = snewn(ntrees * 40, char);
1170 p = *aux;
1171 *p++ = 'S';
1172 for (i = 0; i < w*h; i++)
1173 if (grid[i] == TENT)
1174 p += sprintf(p, ";T%d,%d", i%w, i/w);
1175 *p++ = '\0';
1176 *aux = sresize(*aux, p - *aux, char);
1178 free_scratch(sc);
1179 sfree(flow);
1180 sfree(capacity);
1181 sfree(edges);
1182 sfree(temp);
1183 sfree(soln);
1184 sfree(numbers);
1185 sfree(puzzle);
1186 sfree(grid);
1188 return ret;
1191 static char *validate_desc(game_params *params, char *desc)
1193 int w = params->w, h = params->h;
1194 int area, i;
1196 area = 0;
1197 while (*desc && *desc != ',') {
1198 if (*desc == '_')
1199 area++;
1200 else if (*desc >= 'a' && *desc < 'z')
1201 area += *desc - 'a' + 2;
1202 else if (*desc == 'z')
1203 area += 25;
1204 else if (*desc == '!' || *desc == '-')
1205 /* do nothing */;
1206 else
1207 return "Invalid character in grid specification";
1209 desc++;
1211 if (area < w * h + 1)
1212 return "Not enough data to fill grid";
1213 else if (area > w * h + 1)
1214 return "Too much data to fill grid";
1216 for (i = 0; i < w+h; i++) {
1217 if (!*desc)
1218 return "Not enough numbers given after grid specification";
1219 else if (*desc != ',')
1220 return "Invalid character in number list";
1221 desc++;
1222 while (*desc && isdigit((unsigned char)*desc)) desc++;
1225 if (*desc)
1226 return "Unexpected additional data at end of game description";
1227 return NULL;
1230 static game_state *new_game(midend *me, game_params *params, char *desc)
1232 int w = params->w, h = params->h;
1233 game_state *state = snew(game_state);
1234 int i;
1236 state->p = *params; /* structure copy */
1237 state->grid = snewn(w*h, char);
1238 state->numbers = snew(struct numbers);
1239 state->numbers->refcount = 1;
1240 state->numbers->numbers = snewn(w+h, int);
1241 state->completed = state->used_solve = FALSE;
1243 i = 0;
1244 memset(state->grid, BLANK, w*h);
1246 while (*desc) {
1247 int run, type;
1249 type = TREE;
1251 if (*desc == '_')
1252 run = 0;
1253 else if (*desc >= 'a' && *desc < 'z')
1254 run = *desc - ('a'-1);
1255 else if (*desc == 'z') {
1256 run = 25;
1257 type = BLANK;
1258 } else {
1259 assert(*desc == '!' || *desc == '-');
1260 run = -1;
1261 type = (*desc == '!' ? TENT : NONTENT);
1264 desc++;
1266 i += run;
1267 assert(i >= 0 && i <= w*h);
1268 if (i == w*h) {
1269 assert(type == TREE);
1270 break;
1271 } else {
1272 if (type != BLANK)
1273 state->grid[i++] = type;
1277 for (i = 0; i < w+h; i++) {
1278 assert(*desc == ',');
1279 desc++;
1280 state->numbers->numbers[i] = atoi(desc);
1281 while (*desc && isdigit((unsigned char)*desc)) desc++;
1284 assert(!*desc);
1286 return state;
1289 static game_state *dup_game(game_state *state)
1291 int w = state->p.w, h = state->p.h;
1292 game_state *ret = snew(game_state);
1294 ret->p = state->p; /* structure copy */
1295 ret->grid = snewn(w*h, char);
1296 memcpy(ret->grid, state->grid, w*h);
1297 ret->numbers = state->numbers;
1298 state->numbers->refcount++;
1299 ret->completed = state->completed;
1300 ret->used_solve = state->used_solve;
1302 return ret;
1305 static void free_game(game_state *state)
1307 if (--state->numbers->refcount <= 0) {
1308 sfree(state->numbers->numbers);
1309 sfree(state->numbers);
1311 sfree(state->grid);
1312 sfree(state);
1315 static char *solve_game(game_state *state, game_state *currstate,
1316 char *aux, char **error)
1318 int w = state->p.w, h = state->p.h;
1320 if (aux) {
1322 * If we already have the solution, save ourselves some
1323 * time.
1325 return dupstr(aux);
1326 } else {
1327 struct solver_scratch *sc = new_scratch(w, h);
1328 char *soln;
1329 int ret;
1330 char *move, *p;
1331 int i;
1333 soln = snewn(w*h, char);
1334 ret = tents_solve(w, h, state->grid, state->numbers->numbers,
1335 soln, sc, DIFFCOUNT-1);
1336 free_scratch(sc);
1337 if (ret != 1) {
1338 sfree(soln);
1339 if (ret == 0)
1340 *error = "This puzzle is not self-consistent";
1341 else
1342 *error = "Unable to find a unique solution for this puzzle";
1343 return NULL;
1347 * Construct a move string which turns the current state
1348 * into the solved state.
1350 move = snewn(w*h * 40, char);
1351 p = move;
1352 *p++ = 'S';
1353 for (i = 0; i < w*h; i++)
1354 if (soln[i] == TENT)
1355 p += sprintf(p, ";T%d,%d", i%w, i/w);
1356 *p++ = '\0';
1357 move = sresize(move, p - move, char);
1359 sfree(soln);
1361 return move;
1365 static int game_can_format_as_text_now(game_params *params)
1367 return TRUE;
1370 static char *game_text_format(game_state *state)
1372 int w = state->p.w, h = state->p.h;
1373 char *ret, *p;
1374 int x, y;
1377 * FIXME: We currently do not print the numbers round the edges
1378 * of the grid. I need to work out a sensible way of doing this
1379 * even when the column numbers exceed 9.
1381 * In the absence of those numbers, the result size is h lines
1382 * of w+1 characters each, plus a NUL.
1384 * This function is currently only used by the standalone
1385 * solver; until I make it look more sensible, I won't enable
1386 * it in the main game structure.
1388 ret = snewn(h*(w+1) + 1, char);
1389 p = ret;
1390 for (y = 0; y < h; y++) {
1391 for (x = 0; x < w; x++) {
1392 *p = (state->grid[y*w+x] == BLANK ? '.' :
1393 state->grid[y*w+x] == TREE ? 'T' :
1394 state->grid[y*w+x] == TENT ? '*' :
1395 state->grid[y*w+x] == NONTENT ? '-' : '?');
1396 p++;
1398 *p++ = '\n';
1400 *p++ = '\0';
1402 return ret;
1405 struct game_ui {
1406 int dsx, dsy; /* coords of drag start */
1407 int dex, dey; /* coords of drag end */
1408 int drag_button; /* -1 for none, or a button code */
1409 int drag_ok; /* dragged off the window, to cancel */
1411 int cx, cy, cdisp; /* cursor position, and ?display. */
1414 static game_ui *new_ui(game_state *state)
1416 game_ui *ui = snew(game_ui);
1417 ui->dsx = ui->dsy = -1;
1418 ui->dex = ui->dey = -1;
1419 ui->drag_button = -1;
1420 ui->drag_ok = FALSE;
1421 ui->cx = ui->cy = ui->cdisp = 0;
1422 return ui;
1425 static void free_ui(game_ui *ui)
1427 sfree(ui);
1430 static char *encode_ui(game_ui *ui)
1432 return NULL;
1435 static void decode_ui(game_ui *ui, char *encoding)
1439 static void game_changed_state(game_ui *ui, game_state *oldstate,
1440 game_state *newstate)
1444 struct game_drawstate {
1445 int tilesize;
1446 int started;
1447 game_params p;
1448 int *drawn, *numbersdrawn;
1449 int cx, cy; /* last-drawn cursor pos, or (-1,-1) if absent. */
1452 #define PREFERRED_TILESIZE 32
1453 #define TILESIZE (ds->tilesize)
1454 #define TLBORDER (TILESIZE/2)
1455 #define BRBORDER (TILESIZE*3/2)
1456 #define COORD(x) ( (x) * TILESIZE + TLBORDER )
1457 #define FROMCOORD(x) ( ((x) - TLBORDER + TILESIZE) / TILESIZE - 1 )
1459 #define FLASH_TIME 0.30F
1461 static int drag_xform(game_ui *ui, int x, int y, int v)
1463 int xmin, ymin, xmax, ymax;
1465 xmin = min(ui->dsx, ui->dex);
1466 xmax = max(ui->dsx, ui->dex);
1467 ymin = min(ui->dsy, ui->dey);
1468 ymax = max(ui->dsy, ui->dey);
1470 #ifndef STYLUS_BASED
1472 * Left-dragging has no effect, so we treat a left-drag as a
1473 * single click on dsx,dsy.
1475 if (ui->drag_button == LEFT_BUTTON) {
1476 xmin = xmax = ui->dsx;
1477 ymin = ymax = ui->dsy;
1479 #endif
1481 if (x < xmin || x > xmax || y < ymin || y > ymax)
1482 return v; /* no change outside drag area */
1484 if (v == TREE)
1485 return v; /* trees are inviolate always */
1487 if (xmin == xmax && ymin == ymax) {
1489 * Results of a simple click. Left button sets blanks to
1490 * tents; right button sets blanks to non-tents; either
1491 * button clears a non-blank square.
1492 * If stylus-based however, it loops instead.
1494 if (ui->drag_button == LEFT_BUTTON)
1495 #ifdef STYLUS_BASED
1496 v = (v == BLANK ? TENT : (v == TENT ? NONTENT : BLANK));
1497 else
1498 v = (v == BLANK ? NONTENT : (v == NONTENT ? TENT : BLANK));
1499 #else
1500 v = (v == BLANK ? TENT : BLANK);
1501 else
1502 v = (v == BLANK ? NONTENT : BLANK);
1503 #endif
1504 } else {
1506 * Results of a drag. Left-dragging has no effect.
1507 * Right-dragging sets all blank squares to non-tents and
1508 * has no effect on anything else.
1510 if (ui->drag_button == RIGHT_BUTTON)
1511 v = (v == BLANK ? NONTENT : v);
1512 else
1513 #ifdef STYLUS_BASED
1514 v = (v == BLANK ? NONTENT : v);
1515 #else
1516 /* do nothing */;
1517 #endif
1520 return v;
1523 static char *interpret_move(game_state *state, game_ui *ui, game_drawstate *ds,
1524 int x, int y, int button)
1526 int w = state->p.w, h = state->p.h;
1527 char tmpbuf[80];
1529 if (button == LEFT_BUTTON || button == RIGHT_BUTTON) {
1530 x = FROMCOORD(x);
1531 y = FROMCOORD(y);
1532 if (x < 0 || y < 0 || x >= w || y >= h)
1533 return NULL;
1535 ui->drag_button = button;
1536 ui->dsx = ui->dex = x;
1537 ui->dsy = ui->dey = y;
1538 ui->drag_ok = TRUE;
1539 ui->cdisp = 0;
1540 return ""; /* ui updated */
1543 if ((IS_MOUSE_DRAG(button) || IS_MOUSE_RELEASE(button)) &&
1544 ui->drag_button > 0) {
1545 int xmin, ymin, xmax, ymax;
1546 char *buf, *sep;
1547 int buflen, bufsize, tmplen;
1549 x = FROMCOORD(x);
1550 y = FROMCOORD(y);
1551 if (x < 0 || y < 0 || x >= w || y >= h) {
1552 ui->drag_ok = FALSE;
1553 } else {
1555 * Drags are limited to one row or column. Hence, we
1556 * work out which coordinate is closer to the drag
1557 * start, and move it _to_ the drag start.
1559 if (abs(x - ui->dsx) < abs(y - ui->dsy))
1560 x = ui->dsx;
1561 else
1562 y = ui->dsy;
1564 ui->dex = x;
1565 ui->dey = y;
1567 ui->drag_ok = TRUE;
1570 if (IS_MOUSE_DRAG(button))
1571 return ""; /* ui updated */
1574 * The drag has been released. Enact it.
1576 if (!ui->drag_ok) {
1577 ui->drag_button = -1;
1578 return ""; /* drag was just cancelled */
1581 xmin = min(ui->dsx, ui->dex);
1582 xmax = max(ui->dsx, ui->dex);
1583 ymin = min(ui->dsy, ui->dey);
1584 ymax = max(ui->dsy, ui->dey);
1585 assert(0 <= xmin && xmin <= xmax && xmax < w);
1586 assert(0 <= ymin && ymin <= ymax && ymax < h);
1588 buflen = 0;
1589 bufsize = 256;
1590 buf = snewn(bufsize, char);
1591 sep = "";
1592 for (y = ymin; y <= ymax; y++)
1593 for (x = xmin; x <= xmax; x++) {
1594 int v = drag_xform(ui, x, y, state->grid[y*w+x]);
1595 if (state->grid[y*w+x] != v) {
1596 tmplen = sprintf(tmpbuf, "%s%c%d,%d", sep,
1597 (int)(v == BLANK ? 'B' :
1598 v == TENT ? 'T' : 'N'),
1599 x, y);
1600 sep = ";";
1602 if (buflen + tmplen >= bufsize) {
1603 bufsize = buflen + tmplen + 256;
1604 buf = sresize(buf, bufsize, char);
1607 strcpy(buf+buflen, tmpbuf);
1608 buflen += tmplen;
1612 ui->drag_button = -1; /* drag is terminated */
1614 if (buflen == 0) {
1615 sfree(buf);
1616 return ""; /* ui updated (drag was terminated) */
1617 } else {
1618 buf[buflen] = '\0';
1619 return buf;
1623 if (IS_CURSOR_MOVE(button)) {
1624 move_cursor(button, &ui->cx, &ui->cy, w, h, 0);
1625 ui->cdisp = 1;
1626 return "";
1628 if (ui->cdisp) {
1629 char rep = 0;
1630 int v = state->grid[ui->cy*w+ui->cx];
1632 if (v != TREE) {
1633 #ifdef SINGLE_CURSOR_SELECT
1634 if (button == CURSOR_SELECT)
1635 /* SELECT cycles T, N, B */
1636 rep = v == BLANK ? 'T' : v == TENT ? 'N' : 'B';
1637 #else
1638 if (button == CURSOR_SELECT)
1639 rep = v == BLANK ? 'T' : 'B';
1640 else if (button == CURSOR_SELECT2)
1641 rep = v == BLANK ? 'N' : 'B';
1642 else if (button == 'T' || button == 'N' || button == 'B')
1643 rep = (char)button;
1644 #endif
1647 if (rep) {
1648 sprintf(tmpbuf, "%c%d,%d", (int)rep, ui->cx, ui->cy);
1649 return dupstr(tmpbuf);
1651 } else if (IS_CURSOR_SELECT(button)) {
1652 ui->cdisp = 1;
1653 return "";
1656 return NULL;
1659 static game_state *execute_move(game_state *state, char *move)
1661 int w = state->p.w, h = state->p.h;
1662 char c;
1663 int x, y, m, n, i, j;
1664 game_state *ret = dup_game(state);
1666 while (*move) {
1667 c = *move;
1668 if (c == 'S') {
1669 int i;
1670 ret->used_solve = TRUE;
1672 * Set all non-tree squares to NONTENT. The rest of the
1673 * solve move will fill the tents in over the top.
1675 for (i = 0; i < w*h; i++)
1676 if (ret->grid[i] != TREE)
1677 ret->grid[i] = NONTENT;
1678 move++;
1679 } else if (c == 'B' || c == 'T' || c == 'N') {
1680 move++;
1681 if (sscanf(move, "%d,%d%n", &x, &y, &n) != 2 ||
1682 x < 0 || y < 0 || x >= w || y >= h) {
1683 free_game(ret);
1684 return NULL;
1686 if (ret->grid[y*w+x] == TREE) {
1687 free_game(ret);
1688 return NULL;
1690 ret->grid[y*w+x] = (c == 'B' ? BLANK : c == 'T' ? TENT : NONTENT);
1691 move += n;
1692 } else {
1693 free_game(ret);
1694 return NULL;
1696 if (*move == ';')
1697 move++;
1698 else if (*move) {
1699 free_game(ret);
1700 return NULL;
1705 * Check for completion.
1707 for (i = n = m = 0; i < w*h; i++) {
1708 if (ret->grid[i] == TENT)
1709 n++;
1710 else if (ret->grid[i] == TREE)
1711 m++;
1713 if (n == m) {
1714 int nedges, maxedges, *edges, *capacity, *flow;
1717 * We have the right number of tents, which is a
1718 * precondition for the game being complete. Now check that
1719 * the numbers add up.
1721 for (i = 0; i < w; i++) {
1722 n = 0;
1723 for (j = 0; j < h; j++)
1724 if (ret->grid[j*w+i] == TENT)
1725 n++;
1726 if (ret->numbers->numbers[i] != n)
1727 goto completion_check_done;
1729 for (i = 0; i < h; i++) {
1730 n = 0;
1731 for (j = 0; j < w; j++)
1732 if (ret->grid[i*w+j] == TENT)
1733 n++;
1734 if (ret->numbers->numbers[w+i] != n)
1735 goto completion_check_done;
1738 * Also, check that no two tents are adjacent.
1740 for (y = 0; y < h; y++)
1741 for (x = 0; x < w; x++) {
1742 if (x+1 < w &&
1743 ret->grid[y*w+x] == TENT && ret->grid[y*w+x+1] == TENT)
1744 goto completion_check_done;
1745 if (y+1 < h &&
1746 ret->grid[y*w+x] == TENT && ret->grid[(y+1)*w+x] == TENT)
1747 goto completion_check_done;
1748 if (x+1 < w && y+1 < h) {
1749 if (ret->grid[y*w+x] == TENT &&
1750 ret->grid[(y+1)*w+(x+1)] == TENT)
1751 goto completion_check_done;
1752 if (ret->grid[(y+1)*w+x] == TENT &&
1753 ret->grid[y*w+(x+1)] == TENT)
1754 goto completion_check_done;
1759 * OK; we have the right number of tents, they match the
1760 * numeric clues, and they satisfy the non-adjacency
1761 * criterion. Finally, we need to verify that they can be
1762 * placed in a one-to-one matching with the trees such that
1763 * every tent is orthogonally adjacent to its tree.
1765 * This bit is where the hard work comes in: we have to do
1766 * it by finding such a matching using maxflow.
1768 * So we construct a network with one special source node,
1769 * one special sink node, one node per tent, and one node
1770 * per tree.
1772 maxedges = 6 * m;
1773 edges = snewn(2 * maxedges, int);
1774 capacity = snewn(maxedges, int);
1775 flow = snewn(maxedges, int);
1776 nedges = 0;
1778 * Node numbering:
1780 * 0..w*h trees/tents
1781 * w*h source
1782 * w*h+1 sink
1784 for (y = 0; y < h; y++)
1785 for (x = 0; x < w; x++)
1786 if (ret->grid[y*w+x] == TREE) {
1787 int d;
1790 * Here we use the direction enum declared for
1791 * the solver. We make use of the fact that the
1792 * directions are declared in the order
1793 * U,L,R,D, meaning that we go through the four
1794 * neighbours of any square in numerically
1795 * increasing order.
1797 for (d = 1; d < MAXDIR; d++) {
1798 int x2 = x + dx(d), y2 = y + dy(d);
1799 if (x2 >= 0 && x2 < w && y2 >= 0 && y2 < h &&
1800 ret->grid[y2*w+x2] == TENT) {
1801 assert(nedges < maxedges);
1802 edges[nedges*2] = y*w+x;
1803 edges[nedges*2+1] = y2*w+x2;
1804 capacity[nedges] = 1;
1805 nedges++;
1808 } else if (ret->grid[y*w+x] == TENT) {
1809 assert(nedges < maxedges);
1810 edges[nedges*2] = y*w+x;
1811 edges[nedges*2+1] = w*h+1; /* edge going to sink */
1812 capacity[nedges] = 1;
1813 nedges++;
1815 for (y = 0; y < h; y++)
1816 for (x = 0; x < w; x++)
1817 if (ret->grid[y*w+x] == TREE) {
1818 assert(nedges < maxedges);
1819 edges[nedges*2] = w*h; /* edge coming from source */
1820 edges[nedges*2+1] = y*w+x;
1821 capacity[nedges] = 1;
1822 nedges++;
1824 n = maxflow(w*h+2, w*h, w*h+1, nedges, edges, capacity, flow, NULL);
1826 sfree(flow);
1827 sfree(capacity);
1828 sfree(edges);
1830 if (n != m)
1831 goto completion_check_done;
1834 * We haven't managed to fault the grid on any count. Score!
1836 ret->completed = TRUE;
1838 completion_check_done:
1840 return ret;
1843 /* ----------------------------------------------------------------------
1844 * Drawing routines.
1847 static void game_compute_size(game_params *params, int tilesize,
1848 int *x, int *y)
1850 /* fool the macros */
1851 struct dummy { int tilesize; } dummy, *ds = &dummy;
1852 dummy.tilesize = tilesize;
1854 *x = TLBORDER + BRBORDER + TILESIZE * params->w;
1855 *y = TLBORDER + BRBORDER + TILESIZE * params->h;
1858 static void game_set_size(drawing *dr, game_drawstate *ds,
1859 game_params *params, int tilesize)
1861 ds->tilesize = tilesize;
1864 static float *game_colours(frontend *fe, int *ncolours)
1866 float *ret = snewn(3 * NCOLOURS, float);
1868 frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
1870 ret[COL_GRID * 3 + 0] = 0.0F;
1871 ret[COL_GRID * 3 + 1] = 0.0F;
1872 ret[COL_GRID * 3 + 2] = 0.0F;
1874 ret[COL_GRASS * 3 + 0] = 0.7F;
1875 ret[COL_GRASS * 3 + 1] = 1.0F;
1876 ret[COL_GRASS * 3 + 2] = 0.5F;
1878 ret[COL_TREETRUNK * 3 + 0] = 0.6F;
1879 ret[COL_TREETRUNK * 3 + 1] = 0.4F;
1880 ret[COL_TREETRUNK * 3 + 2] = 0.0F;
1882 ret[COL_TREELEAF * 3 + 0] = 0.0F;
1883 ret[COL_TREELEAF * 3 + 1] = 0.7F;
1884 ret[COL_TREELEAF * 3 + 2] = 0.0F;
1886 ret[COL_TENT * 3 + 0] = 0.8F;
1887 ret[COL_TENT * 3 + 1] = 0.7F;
1888 ret[COL_TENT * 3 + 2] = 0.0F;
1890 ret[COL_ERROR * 3 + 0] = 1.0F;
1891 ret[COL_ERROR * 3 + 1] = 0.0F;
1892 ret[COL_ERROR * 3 + 2] = 0.0F;
1894 ret[COL_ERRTEXT * 3 + 0] = 1.0F;
1895 ret[COL_ERRTEXT * 3 + 1] = 1.0F;
1896 ret[COL_ERRTEXT * 3 + 2] = 1.0F;
1898 ret[COL_ERRTRUNK * 3 + 0] = 0.6F;
1899 ret[COL_ERRTRUNK * 3 + 1] = 0.0F;
1900 ret[COL_ERRTRUNK * 3 + 2] = 0.0F;
1902 *ncolours = NCOLOURS;
1903 return ret;
1906 static game_drawstate *game_new_drawstate(drawing *dr, game_state *state)
1908 int w = state->p.w, h = state->p.h;
1909 struct game_drawstate *ds = snew(struct game_drawstate);
1910 int i;
1912 ds->tilesize = 0;
1913 ds->started = FALSE;
1914 ds->p = state->p; /* structure copy */
1915 ds->drawn = snewn(w*h, int);
1916 for (i = 0; i < w*h; i++)
1917 ds->drawn[i] = MAGIC;
1918 ds->numbersdrawn = snewn(w+h, int);
1919 for (i = 0; i < w+h; i++)
1920 ds->numbersdrawn[i] = 2;
1921 ds->cx = ds->cy = -1;
1923 return ds;
1926 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
1928 sfree(ds->drawn);
1929 sfree(ds->numbersdrawn);
1930 sfree(ds);
1933 enum {
1934 ERR_ADJ_TOPLEFT = 4,
1935 ERR_ADJ_TOP,
1936 ERR_ADJ_TOPRIGHT,
1937 ERR_ADJ_LEFT,
1938 ERR_ADJ_RIGHT,
1939 ERR_ADJ_BOTLEFT,
1940 ERR_ADJ_BOT,
1941 ERR_ADJ_BOTRIGHT,
1942 ERR_OVERCOMMITTED
1945 static int *find_errors(game_state *state, char *grid)
1947 int w = state->p.w, h = state->p.h;
1948 int *ret = snewn(w*h + w + h, int);
1949 int *tmp = snewn(w*h*2, int), *dsf = tmp + w*h;
1950 int x, y;
1953 * This function goes through a grid and works out where to
1954 * highlight play errors in red. The aim is that it should
1955 * produce at least one error highlight for any complete grid
1956 * (or complete piece of grid) violating a puzzle constraint, so
1957 * that a grid containing no BLANK squares is either a win or is
1958 * marked up in some way that indicates why not.
1960 * So it's easy enough to highlight errors in the numeric clues
1961 * - just light up any row or column number which is not
1962 * fulfilled - and it's just as easy to highlight adjacent
1963 * tents. The difficult bit is highlighting failures in the
1964 * tent/tree matching criterion.
1966 * A natural approach would seem to be to apply the maxflow
1967 * algorithm to find the tent/tree matching; if this fails, it
1968 * must necessarily terminate with a min-cut which can be
1969 * reinterpreted as some set of trees which have too few tents
1970 * between them (or vice versa). However, it's bad for
1971 * localising errors, because it's not easy to make the
1972 * algorithm narrow down to the _smallest_ such set of trees: if
1973 * trees A and B have only one tent between them, for instance,
1974 * it might perfectly well highlight not only A and B but also
1975 * trees C and D which are correctly matched on the far side of
1976 * the grid, on the grounds that those four trees between them
1977 * have only three tents.
1979 * Also, that approach fares badly when you introduce the
1980 * additional requirement that incomplete grids should have
1981 * errors highlighted only when they can be proved to be errors
1982 * - so that trees should not be marked as having too few tents
1983 * if there are enough BLANK squares remaining around them that
1984 * could be turned into the missing tents (to do so would be
1985 * patronising, since the overwhelming likelihood is not that
1986 * the player has forgotten to put a tree there but that they
1987 * have merely not put one there _yet_). However, tents with too
1988 * few trees can be marked immediately, since those are
1989 * definitely player error.
1991 * So I adopt an alternative approach, which is to consider the
1992 * bipartite adjacency graph between trees and tents
1993 * ('bipartite' in the sense that for these purposes I
1994 * deliberately ignore two adjacent trees or two adjacent
1995 * tents), divide that graph up into its connected components
1996 * using a dsf, and look for components which contain different
1997 * numbers of trees and tents. This allows me to highlight
1998 * groups of tents with too few trees between them immediately,
1999 * and then in order to find groups of trees with too few tents
2000 * I redo the same process but counting BLANKs as potential
2001 * tents (so that the only trees highlighted are those
2002 * surrounded by enough NONTENTs to make it impossible to give
2003 * them enough tents).
2005 * However, this technique is incomplete: it is not a sufficient
2006 * condition for the existence of a perfect matching that every
2007 * connected component of the graph has the same number of tents
2008 * and trees. An example of a graph which satisfies the latter
2009 * condition but still has no perfect matching is
2011 * A B C
2012 * | / ,/|
2013 * | / ,'/ |
2014 * | / ,' / |
2015 * |/,' / |
2016 * 1 2 3
2018 * which can be realised in Tents as
2021 * A 1 C 2
2024 * The matching-error highlighter described above will not mark
2025 * this construction as erroneous. However, something else will:
2026 * the three tents in the above diagram (let us suppose A,B,C
2027 * are the tents, though it doesn't matter which) contain two
2028 * diagonally adjacent pairs. So there will be _an_ error
2029 * highlighted for the above layout, even though not all types
2030 * of error will be highlighted.
2032 * And in fact we can prove that this will always be the case:
2033 * that the shortcomings of the matching-error highlighter will
2034 * always be made up for by the easy tent adjacency highlighter.
2036 * Lemma: Let G be a bipartite graph between n trees and n
2037 * tents, which is connected, and in which no tree has degree
2038 * more than two (but a tent may). Then G has a perfect matching.
2040 * (Note: in the statement and proof of the Lemma I will
2041 * consistently use 'tree' to indicate a type of graph vertex as
2042 * opposed to a tent, and not to indicate a tree in the graph-
2043 * theoretic sense.)
2045 * Proof:
2047 * If we can find a tent of degree 1 joined to a tree of degree
2048 * 2, then any perfect matching must pair that tent with that
2049 * tree. Hence, we can remove both, leaving a smaller graph G'
2050 * which still satisfies all the conditions of the Lemma, and
2051 * which has a perfect matching iff G does.
2053 * So, wlog, we may assume G contains no tent of degree 1 joined
2054 * to a tree of degree 2; if it does, we can reduce it as above.
2056 * If G has no tent of degree 1 at all, then every tent has
2057 * degree at least two, so there are at least 2n edges in the
2058 * graph. But every tree has degree at most two, so there are at
2059 * most 2n edges. Hence there must be exactly 2n edges, so every
2060 * tree and every tent must have degree exactly two, which means
2061 * that the whole graph consists of a single loop (by
2062 * connectedness), and therefore certainly has a perfect
2063 * matching.
2065 * Alternatively, if G does have a tent of degree 1 but it is
2066 * not connected to a tree of degree 2, then the tree it is
2067 * connected to must have degree 1 - and, by connectedness, that
2068 * must mean that that tent and that tree between them form the
2069 * entire graph. This trivial graph has a trivial perfect
2070 * matching. []
2072 * That proves the lemma. Hence, in any case where the matching-
2073 * error highlighter fails to highlight an erroneous component
2074 * (because it has the same number of tents as trees, but they
2075 * cannot be matched up), the above lemma tells us that there
2076 * must be a tree with degree more than 2, i.e. a tree
2077 * orthogonally adjacent to at least three tents. But in that
2078 * case, there must be some pair of those three tents which are
2079 * diagonally adjacent to each other, so the tent-adjacency
2080 * highlighter will necessarily show an error. So any filled
2081 * layout in Tents which is not a correct solution to the puzzle
2082 * must have _some_ error highlighted by the subroutine below.
2084 * (Of course it would be nicer if we could highlight all
2085 * errors: in the above example layout, we would like to
2086 * highlight tents A,B as having too few trees between them, and
2087 * trees 2,3 as having too few tents, in addition to marking the
2088 * adjacency problems. But I can't immediately think of any way
2089 * to find the smallest sets of such tents and trees without an
2090 * O(2^N) loop over all subsets of a given component.)
2094 * ret[0] through to ret[w*h-1] give error markers for the grid
2095 * squares. After that, ret[w*h] to ret[w*h+w-1] give error
2096 * markers for the column numbers, and ret[w*h+w] to
2097 * ret[w*h+w+h-1] for the row numbers.
2101 * Spot tent-adjacency violations.
2103 for (x = 0; x < w*h; x++)
2104 ret[x] = 0;
2105 for (y = 0; y < h; y++) {
2106 for (x = 0; x < w; x++) {
2107 if (y+1 < h && x+1 < w &&
2108 ((grid[y*w+x] == TENT &&
2109 grid[(y+1)*w+(x+1)] == TENT) ||
2110 (grid[(y+1)*w+x] == TENT &&
2111 grid[y*w+(x+1)] == TENT))) {
2112 ret[y*w+x] |= 1 << ERR_ADJ_BOTRIGHT;
2113 ret[(y+1)*w+x] |= 1 << ERR_ADJ_TOPRIGHT;
2114 ret[y*w+(x+1)] |= 1 << ERR_ADJ_BOTLEFT;
2115 ret[(y+1)*w+(x+1)] |= 1 << ERR_ADJ_TOPLEFT;
2117 if (y+1 < h &&
2118 grid[y*w+x] == TENT &&
2119 grid[(y+1)*w+x] == TENT) {
2120 ret[y*w+x] |= 1 << ERR_ADJ_BOT;
2121 ret[(y+1)*w+x] |= 1 << ERR_ADJ_TOP;
2123 if (x+1 < w &&
2124 grid[y*w+x] == TENT &&
2125 grid[y*w+(x+1)] == TENT) {
2126 ret[y*w+x] |= 1 << ERR_ADJ_RIGHT;
2127 ret[y*w+(x+1)] |= 1 << ERR_ADJ_LEFT;
2133 * Spot numeric clue violations.
2135 for (x = 0; x < w; x++) {
2136 int tents = 0, maybetents = 0;
2137 for (y = 0; y < h; y++) {
2138 if (grid[y*w+x] == TENT)
2139 tents++;
2140 else if (grid[y*w+x] == BLANK)
2141 maybetents++;
2143 ret[w*h+x] = (tents > state->numbers->numbers[x] ||
2144 tents + maybetents < state->numbers->numbers[x]);
2146 for (y = 0; y < h; y++) {
2147 int tents = 0, maybetents = 0;
2148 for (x = 0; x < w; x++) {
2149 if (grid[y*w+x] == TENT)
2150 tents++;
2151 else if (grid[y*w+x] == BLANK)
2152 maybetents++;
2154 ret[w*h+w+y] = (tents > state->numbers->numbers[w+y] ||
2155 tents + maybetents < state->numbers->numbers[w+y]);
2159 * Identify groups of tents with too few trees between them,
2160 * which we do by constructing the connected components of the
2161 * bipartite adjacency graph between tents and trees
2162 * ('bipartite' in the sense that we deliberately ignore
2163 * adjacency between tents or between trees), and highlighting
2164 * all the tents in any component which has a smaller tree
2165 * count.
2167 dsf_init(dsf, w*h);
2168 /* Construct the equivalence classes. */
2169 for (y = 0; y < h; y++) {
2170 for (x = 0; x < w-1; x++) {
2171 if ((grid[y*w+x] == TREE && grid[y*w+x+1] == TENT) ||
2172 (grid[y*w+x] == TENT && grid[y*w+x+1] == TREE))
2173 dsf_merge(dsf, y*w+x, y*w+x+1);
2176 for (y = 0; y < h-1; y++) {
2177 for (x = 0; x < w; x++) {
2178 if ((grid[y*w+x] == TREE && grid[(y+1)*w+x] == TENT) ||
2179 (grid[y*w+x] == TENT && grid[(y+1)*w+x] == TREE))
2180 dsf_merge(dsf, y*w+x, (y+1)*w+x);
2183 /* Count up the tent/tree difference in each one. */
2184 for (x = 0; x < w*h; x++)
2185 tmp[x] = 0;
2186 for (x = 0; x < w*h; x++) {
2187 y = dsf_canonify(dsf, x);
2188 if (grid[x] == TREE)
2189 tmp[y]++;
2190 else if (grid[x] == TENT)
2191 tmp[y]--;
2193 /* And highlight any tent belonging to an equivalence class with
2194 * a score less than zero. */
2195 for (x = 0; x < w*h; x++) {
2196 y = dsf_canonify(dsf, x);
2197 if (grid[x] == TENT && tmp[y] < 0)
2198 ret[x] |= 1 << ERR_OVERCOMMITTED;
2202 * Identify groups of trees with too few tents between them.
2203 * This is done similarly, except that we now count BLANK as
2204 * equivalent to TENT, i.e. we only highlight such trees when
2205 * the user hasn't even left _room_ to provide tents for them
2206 * all. (Otherwise, we'd highlight all trees red right at the
2207 * start of the game, before the user had done anything wrong!)
2209 #define TENT(x) ((x)==TENT || (x)==BLANK)
2210 dsf_init(dsf, w*h);
2211 /* Construct the equivalence classes. */
2212 for (y = 0; y < h; y++) {
2213 for (x = 0; x < w-1; x++) {
2214 if ((grid[y*w+x] == TREE && TENT(grid[y*w+x+1])) ||
2215 (TENT(grid[y*w+x]) && grid[y*w+x+1] == TREE))
2216 dsf_merge(dsf, y*w+x, y*w+x+1);
2219 for (y = 0; y < h-1; y++) {
2220 for (x = 0; x < w; x++) {
2221 if ((grid[y*w+x] == TREE && TENT(grid[(y+1)*w+x])) ||
2222 (TENT(grid[y*w+x]) && grid[(y+1)*w+x] == TREE))
2223 dsf_merge(dsf, y*w+x, (y+1)*w+x);
2226 /* Count up the tent/tree difference in each one. */
2227 for (x = 0; x < w*h; x++)
2228 tmp[x] = 0;
2229 for (x = 0; x < w*h; x++) {
2230 y = dsf_canonify(dsf, x);
2231 if (grid[x] == TREE)
2232 tmp[y]++;
2233 else if (TENT(grid[x]))
2234 tmp[y]--;
2236 /* And highlight any tree belonging to an equivalence class with
2237 * a score more than zero. */
2238 for (x = 0; x < w*h; x++) {
2239 y = dsf_canonify(dsf, x);
2240 if (grid[x] == TREE && tmp[y] > 0)
2241 ret[x] |= 1 << ERR_OVERCOMMITTED;
2243 #undef TENT
2245 sfree(tmp);
2246 return ret;
2249 static void draw_err_adj(drawing *dr, game_drawstate *ds, int x, int y)
2251 int coords[8];
2252 int yext, xext;
2255 * Draw a diamond.
2257 coords[0] = x - TILESIZE*2/5;
2258 coords[1] = y;
2259 coords[2] = x;
2260 coords[3] = y - TILESIZE*2/5;
2261 coords[4] = x + TILESIZE*2/5;
2262 coords[5] = y;
2263 coords[6] = x;
2264 coords[7] = y + TILESIZE*2/5;
2265 draw_polygon(dr, coords, 4, COL_ERROR, COL_GRID);
2268 * Draw an exclamation mark in the diamond. This turns out to
2269 * look unpleasantly off-centre if done via draw_text, so I do
2270 * it by hand on the basis that exclamation marks aren't that
2271 * difficult to draw...
2273 xext = TILESIZE/16;
2274 yext = TILESIZE*2/5 - (xext*2+2);
2275 draw_rect(dr, x-xext, y-yext, xext*2+1, yext*2+1 - (xext*3),
2276 COL_ERRTEXT);
2277 draw_rect(dr, x-xext, y+yext-xext*2+1, xext*2+1, xext*2, COL_ERRTEXT);
2280 static void draw_tile(drawing *dr, game_drawstate *ds,
2281 int x, int y, int v, int cur, int printing)
2283 int err;
2284 int tx = COORD(x), ty = COORD(y);
2285 int cx = tx + TILESIZE/2, cy = ty + TILESIZE/2;
2287 err = v & ~15;
2288 v &= 15;
2290 clip(dr, tx, ty, TILESIZE, TILESIZE);
2292 if (!printing) {
2293 draw_rect(dr, tx, ty, TILESIZE, TILESIZE, COL_GRID);
2294 draw_rect(dr, tx+1, ty+1, TILESIZE-1, TILESIZE-1,
2295 (v == BLANK ? COL_BACKGROUND : COL_GRASS));
2298 if (v == TREE) {
2299 int i;
2301 (printing ? draw_rect_outline : draw_rect)
2302 (dr, cx-TILESIZE/15, ty+TILESIZE*3/10,
2303 2*(TILESIZE/15)+1, (TILESIZE*9/10 - TILESIZE*3/10),
2304 (err & (1<<ERR_OVERCOMMITTED) ? COL_ERRTRUNK : COL_TREETRUNK));
2306 for (i = 0; i < (printing ? 2 : 1); i++) {
2307 int col = (i == 1 ? COL_BACKGROUND :
2308 (err & (1<<ERR_OVERCOMMITTED) ? COL_ERROR :
2309 COL_TREELEAF));
2310 int sub = i * (TILESIZE/32);
2311 draw_circle(dr, cx, ty+TILESIZE*4/10, TILESIZE/4 - sub,
2312 col, col);
2313 draw_circle(dr, cx+TILESIZE/5, ty+TILESIZE/4, TILESIZE/8 - sub,
2314 col, col);
2315 draw_circle(dr, cx-TILESIZE/5, ty+TILESIZE/4, TILESIZE/8 - sub,
2316 col, col);
2317 draw_circle(dr, cx+TILESIZE/4, ty+TILESIZE*6/13, TILESIZE/8 - sub,
2318 col, col);
2319 draw_circle(dr, cx-TILESIZE/4, ty+TILESIZE*6/13, TILESIZE/8 - sub,
2320 col, col);
2322 } else if (v == TENT) {
2323 int coords[6];
2324 int col;
2325 coords[0] = cx - TILESIZE/3;
2326 coords[1] = cy + TILESIZE/3;
2327 coords[2] = cx + TILESIZE/3;
2328 coords[3] = cy + TILESIZE/3;
2329 coords[4] = cx;
2330 coords[5] = cy - TILESIZE/3;
2331 col = (err & (1<<ERR_OVERCOMMITTED) ? COL_ERROR : COL_TENT);
2332 draw_polygon(dr, coords, 3, (printing ? -1 : col), col);
2335 if (err & (1 << ERR_ADJ_TOPLEFT))
2336 draw_err_adj(dr, ds, tx, ty);
2337 if (err & (1 << ERR_ADJ_TOP))
2338 draw_err_adj(dr, ds, tx+TILESIZE/2, ty);
2339 if (err & (1 << ERR_ADJ_TOPRIGHT))
2340 draw_err_adj(dr, ds, tx+TILESIZE, ty);
2341 if (err & (1 << ERR_ADJ_LEFT))
2342 draw_err_adj(dr, ds, tx, ty+TILESIZE/2);
2343 if (err & (1 << ERR_ADJ_RIGHT))
2344 draw_err_adj(dr, ds, tx+TILESIZE, ty+TILESIZE/2);
2345 if (err & (1 << ERR_ADJ_BOTLEFT))
2346 draw_err_adj(dr, ds, tx, ty+TILESIZE);
2347 if (err & (1 << ERR_ADJ_BOT))
2348 draw_err_adj(dr, ds, tx+TILESIZE/2, ty+TILESIZE);
2349 if (err & (1 << ERR_ADJ_BOTRIGHT))
2350 draw_err_adj(dr, ds, tx+TILESIZE, ty+TILESIZE);
2352 if (cur) {
2353 int coff = TILESIZE/8;
2354 draw_rect_outline(dr, tx + coff, ty + coff,
2355 TILESIZE - coff*2 + 1, TILESIZE - coff*2 + 1,
2356 COL_GRID);
2359 unclip(dr);
2360 draw_update(dr, tx+1, ty+1, TILESIZE-1, TILESIZE-1);
2364 * Internal redraw function, used for printing as well as drawing.
2366 static void int_redraw(drawing *dr, game_drawstate *ds, game_state *oldstate,
2367 game_state *state, int dir, game_ui *ui,
2368 float animtime, float flashtime, int printing)
2370 int w = state->p.w, h = state->p.h;
2371 int x, y, flashing;
2372 int cx = -1, cy = -1;
2373 int cmoved = 0;
2374 char *tmpgrid;
2375 int *errors;
2377 if (ui) {
2378 if (ui->cdisp) { cx = ui->cx; cy = ui->cy; }
2379 if (cx != ds->cx || cy != ds->cy) cmoved = 1;
2382 if (printing || !ds->started) {
2383 if (!printing) {
2384 int ww, wh;
2385 game_compute_size(&state->p, TILESIZE, &ww, &wh);
2386 draw_rect(dr, 0, 0, ww, wh, COL_BACKGROUND);
2387 draw_update(dr, 0, 0, ww, wh);
2388 ds->started = TRUE;
2391 if (printing)
2392 print_line_width(dr, TILESIZE/64);
2395 * Draw the grid.
2397 for (y = 0; y <= h; y++)
2398 draw_line(dr, COORD(0), COORD(y), COORD(w), COORD(y), COL_GRID);
2399 for (x = 0; x <= w; x++)
2400 draw_line(dr, COORD(x), COORD(0), COORD(x), COORD(h), COL_GRID);
2403 if (flashtime > 0)
2404 flashing = (int)(flashtime * 3 / FLASH_TIME) != 1;
2405 else
2406 flashing = FALSE;
2409 * Find errors. For this we use _part_ of the information from a
2410 * currently active drag: we transform dsx,dsy but not anything
2411 * else. (This seems to strike a good compromise between having
2412 * the error highlights respond instantly to single clicks, but
2413 * not giving constant feedback during a right-drag.)
2415 if (ui && ui->drag_button >= 0) {
2416 tmpgrid = snewn(w*h, char);
2417 memcpy(tmpgrid, state->grid, w*h);
2418 tmpgrid[ui->dsy * w + ui->dsx] =
2419 drag_xform(ui, ui->dsx, ui->dsy, tmpgrid[ui->dsy * w + ui->dsx]);
2420 errors = find_errors(state, tmpgrid);
2421 sfree(tmpgrid);
2422 } else {
2423 errors = find_errors(state, state->grid);
2427 * Draw the grid.
2429 for (y = 0; y < h; y++) {
2430 for (x = 0; x < w; x++) {
2431 int v = state->grid[y*w+x];
2432 int credraw = 0;
2435 * We deliberately do not take drag_ok into account
2436 * here, because user feedback suggests that it's
2437 * marginally nicer not to have the drag effects
2438 * flickering on and off disconcertingly.
2440 if (ui && ui->drag_button >= 0)
2441 v = drag_xform(ui, x, y, v);
2443 if (flashing && (v == TREE || v == TENT))
2444 v = NONTENT;
2446 if (cmoved) {
2447 if ((x == cx && y == cy) ||
2448 (x == ds->cx && y == ds->cy)) credraw = 1;
2451 v |= errors[y*w+x];
2453 if (printing || ds->drawn[y*w+x] != v || credraw) {
2454 draw_tile(dr, ds, x, y, v, (x == cx && y == cy), printing);
2455 if (!printing)
2456 ds->drawn[y*w+x] = v;
2462 * Draw (or redraw, if their error-highlighted state has
2463 * changed) the numbers.
2465 for (x = 0; x < w; x++) {
2466 if (printing || ds->numbersdrawn[x] != errors[w*h+x]) {
2467 char buf[80];
2468 draw_rect(dr, COORD(x), COORD(h)+1, TILESIZE, BRBORDER-1,
2469 COL_BACKGROUND);
2470 sprintf(buf, "%d", state->numbers->numbers[x]);
2471 draw_text(dr, COORD(x) + TILESIZE/2, COORD(h+1),
2472 FONT_VARIABLE, TILESIZE/2, ALIGN_HCENTRE|ALIGN_VNORMAL,
2473 (errors[w*h+x] ? COL_ERROR : COL_GRID), buf);
2474 draw_update(dr, COORD(x), COORD(h)+1, TILESIZE, BRBORDER-1);
2475 if (!printing)
2476 ds->numbersdrawn[x] = errors[w*h+x];
2479 for (y = 0; y < h; y++) {
2480 if (printing || ds->numbersdrawn[w+y] != errors[w*h+w+y]) {
2481 char buf[80];
2482 draw_rect(dr, COORD(w)+1, COORD(y), BRBORDER-1, TILESIZE,
2483 COL_BACKGROUND);
2484 sprintf(buf, "%d", state->numbers->numbers[w+y]);
2485 draw_text(dr, COORD(w+1), COORD(y) + TILESIZE/2,
2486 FONT_VARIABLE, TILESIZE/2, ALIGN_HRIGHT|ALIGN_VCENTRE,
2487 (errors[w*h+w+y] ? COL_ERROR : COL_GRID), buf);
2488 draw_update(dr, COORD(w)+1, COORD(y), BRBORDER-1, TILESIZE);
2489 if (!printing)
2490 ds->numbersdrawn[w+y] = errors[w*h+w+y];
2494 if (cmoved) {
2495 ds->cx = cx;
2496 ds->cy = cy;
2499 sfree(errors);
2502 static void game_redraw(drawing *dr, game_drawstate *ds, game_state *oldstate,
2503 game_state *state, int dir, game_ui *ui,
2504 float animtime, float flashtime)
2506 int_redraw(dr, ds, oldstate, state, dir, ui, animtime, flashtime, FALSE);
2509 static float game_anim_length(game_state *oldstate, game_state *newstate,
2510 int dir, game_ui *ui)
2512 return 0.0F;
2515 static float game_flash_length(game_state *oldstate, game_state *newstate,
2516 int dir, game_ui *ui)
2518 if (!oldstate->completed && newstate->completed &&
2519 !oldstate->used_solve && !newstate->used_solve)
2520 return FLASH_TIME;
2522 return 0.0F;
2525 static int game_status(game_state *state)
2527 return state->completed ? +1 : 0;
2530 static int game_timing_state(game_state *state, game_ui *ui)
2532 return TRUE;
2535 static void game_print_size(game_params *params, float *x, float *y)
2537 int pw, ph;
2540 * I'll use 6mm squares by default.
2542 game_compute_size(params, 600, &pw, &ph);
2543 *x = pw / 100.0F;
2544 *y = ph / 100.0F;
2547 static void game_print(drawing *dr, game_state *state, int tilesize)
2549 int c;
2551 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
2552 game_drawstate ads, *ds = &ads;
2553 game_set_size(dr, ds, NULL, tilesize);
2555 c = print_mono_colour(dr, 1); assert(c == COL_BACKGROUND);
2556 c = print_mono_colour(dr, 0); assert(c == COL_GRID);
2557 c = print_mono_colour(dr, 1); assert(c == COL_GRASS);
2558 c = print_mono_colour(dr, 0); assert(c == COL_TREETRUNK);
2559 c = print_mono_colour(dr, 0); assert(c == COL_TREELEAF);
2560 c = print_mono_colour(dr, 0); assert(c == COL_TENT);
2562 int_redraw(dr, ds, NULL, state, +1, NULL, 0.0F, 0.0F, TRUE);
2565 #ifdef COMBINED
2566 #define thegame tents
2567 #endif
2569 const struct game thegame = {
2570 "Tents", "games.tents", "tents",
2571 default_params,
2572 game_fetch_preset,
2573 decode_params,
2574 encode_params,
2575 free_params,
2576 dup_params,
2577 TRUE, game_configure, custom_params,
2578 validate_params,
2579 new_game_desc,
2580 validate_desc,
2581 new_game,
2582 dup_game,
2583 free_game,
2584 TRUE, solve_game,
2585 FALSE, game_can_format_as_text_now, game_text_format,
2586 new_ui,
2587 free_ui,
2588 encode_ui,
2589 decode_ui,
2590 game_changed_state,
2591 interpret_move,
2592 execute_move,
2593 PREFERRED_TILESIZE, game_compute_size, game_set_size,
2594 game_colours,
2595 game_new_drawstate,
2596 game_free_drawstate,
2597 game_redraw,
2598 game_anim_length,
2599 game_flash_length,
2600 game_status,
2601 TRUE, FALSE, game_print_size, game_print,
2602 FALSE, /* wants_statusbar */
2603 FALSE, game_timing_state,
2604 REQUIRE_RBUTTON, /* flags */
2607 #ifdef STANDALONE_SOLVER
2609 #include <stdarg.h>
2611 int main(int argc, char **argv)
2613 game_params *p;
2614 game_state *s, *s2;
2615 char *id = NULL, *desc, *err;
2616 int grade = FALSE;
2617 int ret, diff, really_verbose = FALSE;
2618 struct solver_scratch *sc;
2620 while (--argc > 0) {
2621 char *p = *++argv;
2622 if (!strcmp(p, "-v")) {
2623 really_verbose = TRUE;
2624 } else if (!strcmp(p, "-g")) {
2625 grade = TRUE;
2626 } else if (*p == '-') {
2627 fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
2628 return 1;
2629 } else {
2630 id = p;
2634 if (!id) {
2635 fprintf(stderr, "usage: %s [-g | -v] <game_id>\n", argv[0]);
2636 return 1;
2639 desc = strchr(id, ':');
2640 if (!desc) {
2641 fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
2642 return 1;
2644 *desc++ = '\0';
2646 p = default_params();
2647 decode_params(p, id);
2648 err = validate_desc(p, desc);
2649 if (err) {
2650 fprintf(stderr, "%s: %s\n", argv[0], err);
2651 return 1;
2653 s = new_game(NULL, p, desc);
2654 s2 = new_game(NULL, p, desc);
2656 sc = new_scratch(p->w, p->h);
2659 * When solving an Easy puzzle, we don't want to bother the
2660 * user with Hard-level deductions. For this reason, we grade
2661 * the puzzle internally before doing anything else.
2663 ret = -1; /* placate optimiser */
2664 for (diff = 0; diff < DIFFCOUNT; diff++) {
2665 ret = tents_solve(p->w, p->h, s->grid, s->numbers->numbers,
2666 s2->grid, sc, diff);
2667 if (ret < 2)
2668 break;
2671 if (diff == DIFFCOUNT) {
2672 if (grade)
2673 printf("Difficulty rating: too hard to solve internally\n");
2674 else
2675 printf("Unable to find a unique solution\n");
2676 } else {
2677 if (grade) {
2678 if (ret == 0)
2679 printf("Difficulty rating: impossible (no solution exists)\n");
2680 else if (ret == 1)
2681 printf("Difficulty rating: %s\n", tents_diffnames[diff]);
2682 } else {
2683 verbose = really_verbose;
2684 ret = tents_solve(p->w, p->h, s->grid, s->numbers->numbers,
2685 s2->grid, sc, diff);
2686 if (ret == 0)
2687 printf("Puzzle is inconsistent\n");
2688 else
2689 fputs(game_text_format(s2), stdout);
2693 return 0;
2696 #endif
2698 /* vim: set shiftwidth=4 tabstop=8: */