Merge commit '6526' into HEAD
[sgt-puzzles/ydirson.git] / loopy.c
blobba305028d9ce8a5fc3d59e014916f501655c2bf8
1 /*
2 * loopy.c: An implementation of the Nikoli game 'Loop the loop'.
3 * (c) Mike Pinna, 2005
5 * vim: set shiftwidth=4 :set textwidth=80:
6 */
8 /*
9 * TODO:
11 * - setting very high recursion depth seems to cause memory
12 * munching: are we recursing before checking completion, by any
13 * chance?
15 * - there's an interesting deductive technique which makes use of
16 * topology rather than just graph theory. Each _square_ in the
17 * grid is either inside or outside the loop; you can tell that
18 * two squares are on the same side of the loop if they're
19 * separated by an x (or, more generally, by a path crossing no
20 * LINE_UNKNOWNs and an even number of LINE_YESes), and on the
21 * opposite side of the loop if they're separated by a line (or
22 * an odd number of LINE_YESes and no LINE_UNKNOWNs). Oh, and
23 * any square separated from the outside of the grid by a
24 * LINE_YES or a LINE_NO is on the inside or outside
25 * respectively. So if you can track this for all squares, you
26 * can occasionally spot that two squares are separated by a
27 * LINE_UNKNOWN but their relative insideness is known, and
28 * therefore deduce the state of the edge between them.
29 * + An efficient way to track this would be by augmenting the
30 * disjoint set forest data structure. Each element, along
31 * with a pointer to a parent member of its equivalence
32 * class, would also carry a one-bit field indicating whether
33 * it was equal or opposite to its parent. Then you could
34 * keep flipping a bit as you ascended the tree during
35 * dsf_canonify(), and hence you'd be able to return the
36 * relationship of the input value to its ultimate parent
37 * (and also you could then get all those bits right when you
38 * went back up the tree rewriting). So you'd be able to
39 * query whether any two elements were known-equal,
40 * known-opposite, or not-known, and you could add new
41 * equalities or oppositenesses to increase your knowledge.
42 * (Of course the algorithm would have to fail an assertion
43 * if you tried to tell it two things it already knew to be
44 * opposite were equal, or vice versa!)
45 * This data structure would also be useful in the
46 * graph-theoretic part of the solver, where it could be used
47 * for storing information about which lines are known-identical
48 * or known-opposite. (For example if two lines bordering a 3
49 * are known-identical they must both be LINE_YES, and if they
50 * are known-opposite, the *other* two lines bordering that clue
51 * must be LINE_YES, etc). This may duplicate some
52 * functionality already present in the solver but it is more
53 * general and we could remove the old code, so that's no bad
54 * thing.
57 #include <stdio.h>
58 #include <stdlib.h>
59 #include <string.h>
60 #include <assert.h>
61 #include <ctype.h>
62 #include <math.h>
64 #include "puzzles.h"
65 #include "tree234.h"
67 #define PREFERRED_TILE_SIZE 32
68 #define TILE_SIZE (ds->tilesize)
69 #define LINEWIDTH (ds->linewidth)
70 #define BORDER (TILE_SIZE / 2)
72 #define FLASH_TIME 0.5F
74 #define HL_COUNT(state) ((state)->w * ((state)->h + 1))
75 #define VL_COUNT(state) (((state)->w + 1) * (state)->h)
76 #define DOT_COUNT(state) (((state)->w + 1) * ((state)->h + 1))
77 #define SQUARE_COUNT(state) ((state)->w * (state)->h)
79 #define ABOVE_SQUARE(state, i, j) ((state)->hl[(i) + (state)->w * (j)])
80 #define BELOW_SQUARE(state, i, j) ABOVE_SQUARE(state, i, (j)+1)
82 #define LEFTOF_SQUARE(state, i, j) ((state)->vl[(i) + ((state)->w + 1) * (j)])
83 #define RIGHTOF_SQUARE(state, i, j) LEFTOF_SQUARE(state, (i)+1, j)
85 #define LEGAL_DOT(state, i, j) ((i) >= 0 && (j) >= 0 && \
86 (i) <= (state)->w && (j) <= (state)->h)
89 * These macros return rvalues only, but can cope with being passed
90 * out-of-range coordinates.
92 #define ABOVE_DOT(state, i, j) ((!LEGAL_DOT(state, i, j) || j <= 0) ? \
93 LINE_NO : LV_ABOVE_DOT(state, i, j))
94 #define BELOW_DOT(state, i, j) ((!LEGAL_DOT(state, i, j) || j >= (state)->h) ? \
95 LINE_NO : LV_BELOW_DOT(state, i, j))
97 #define LEFTOF_DOT(state, i, j) ((!LEGAL_DOT(state, i, j) || i <= 0) ? \
98 LINE_NO : LV_LEFTOF_DOT(state, i, j))
99 #define RIGHTOF_DOT(state, i, j) ((!LEGAL_DOT(state, i, j) || i >= (state)->w)?\
100 LINE_NO : LV_RIGHTOF_DOT(state, i, j))
103 * These macros expect to be passed valid coordinates, and return
104 * lvalues.
106 #define LV_BELOW_DOT(state, i, j) ((state)->vl[(i) + ((state)->w + 1) * (j)])
107 #define LV_ABOVE_DOT(state, i, j) LV_BELOW_DOT(state, i, (j)-1)
109 #define LV_RIGHTOF_DOT(state, i, j) ((state)->hl[(i) + (state)->w * (j)])
110 #define LV_LEFTOF_DOT(state, i, j) LV_RIGHTOF_DOT(state, (i)-1, j)
112 #define CLUE_AT(state, i, j) ((i < 0 || i >= (state)->w || \
113 j < 0 || j >= (state)->h) ? \
114 ' ' : LV_CLUE_AT(state, i, j))
116 #define LV_CLUE_AT(state, i, j) ((state)->clues[(i) + (state)->w * (j)])
118 #define OPP(dir) (dir == LINE_UNKNOWN ? LINE_UNKNOWN : \
119 dir == LINE_YES ? LINE_NO : LINE_YES)
121 #define BIT_SET(field, bit) ((field) & (1<<(bit)))
123 #define SET_BIT(field, bit) (BIT_SET(field, bit) ? FALSE : \
124 ((field) |= (1<<(bit)), TRUE))
126 #define CLEAR_BIT(field, bit) (BIT_SET(field, bit) ? \
127 ((field) &= ~(1<<(bit)), TRUE) : FALSE)
129 static char *game_text_format(game_state *state);
131 enum {
132 COL_BACKGROUND,
133 COL_FOREGROUND,
134 COL_HIGHLIGHT,
135 COL_MISTAKE,
136 NCOLOURS
140 * Difficulty levels. I do some macro ickery here to ensure that my
141 * enum and the various forms of my name list always match up.
143 #define DIFFLIST(A) \
144 A(EASY,Easy,e) \
145 A(NORMAL,Normal,n)
146 #define ENUM(upper,title,lower) DIFF_ ## upper,
147 #define TITLE(upper,title,lower) #title,
148 #define ENCODE(upper,title,lower) #lower
149 #define CONFIG(upper,title,lower) ":" #title
150 enum { DIFFLIST(ENUM) DIFFCOUNT };
151 /* static char const *const loopy_diffnames[] = { DIFFLIST(TITLE) }; */
152 static char const loopy_diffchars[] = DIFFLIST(ENCODE);
153 #define DIFFCONFIG DIFFLIST(CONFIG)
155 /* LINE_YES_ERROR is only used in the drawing routine */
156 enum line_state { LINE_UNKNOWN, LINE_YES, LINE_NO /*, LINE_YES_ERROR*/ };
158 enum direction { UP, DOWN, LEFT, RIGHT };
160 struct game_params {
161 int w, h, diff, rec;
164 struct game_state {
165 int w, h;
167 /* Put ' ' in a square that doesn't get a clue */
168 char *clues;
170 /* Arrays of line states, stored left-to-right, top-to-bottom */
171 char *hl, *vl;
173 int solved;
174 int cheated;
176 int recursion_depth;
179 static game_state *dup_game(game_state *state)
181 game_state *ret = snew(game_state);
183 ret->h = state->h;
184 ret->w = state->w;
185 ret->solved = state->solved;
186 ret->cheated = state->cheated;
188 ret->clues = snewn(SQUARE_COUNT(state), char);
189 memcpy(ret->clues, state->clues, SQUARE_COUNT(state));
191 ret->hl = snewn(HL_COUNT(state), char);
192 memcpy(ret->hl, state->hl, HL_COUNT(state));
194 ret->vl = snewn(VL_COUNT(state), char);
195 memcpy(ret->vl, state->vl, VL_COUNT(state));
197 ret->recursion_depth = state->recursion_depth;
199 return ret;
202 static void free_game(game_state *state)
204 if (state) {
205 sfree(state->clues);
206 sfree(state->hl);
207 sfree(state->vl);
208 sfree(state);
212 enum solver_status {
213 SOLVER_SOLVED, /* This is the only solution the solver could find */
214 SOLVER_MISTAKE, /* This is definitely not a solution */
215 SOLVER_AMBIGUOUS, /* This _might_ be an ambiguous solution */
216 SOLVER_INCOMPLETE /* This may be a partial solution */
219 typedef struct solver_state {
220 game_state *state;
221 char *dot_atleastone;
222 char *dot_atmostone;
223 /* char *dline_identical; */
224 int recursion_remaining;
225 enum solver_status solver_status;
226 /* NB looplen is the number of dots that are joined together at a point, ie a
227 * looplen of 1 means there are no lines to a particular dot */
228 int *dotdsf, *looplen;
229 } solver_state;
231 static solver_state *new_solver_state(game_state *state) {
232 solver_state *ret = snew(solver_state);
233 int i;
235 ret->state = dup_game(state);
237 ret->dot_atmostone = snewn(DOT_COUNT(state), char);
238 memset(ret->dot_atmostone, 0, DOT_COUNT(state));
239 ret->dot_atleastone = snewn(DOT_COUNT(state), char);
240 memset(ret->dot_atleastone, 0, DOT_COUNT(state));
242 #if 0
243 dline_identical = snewn(DOT_COUNT(state), char);
244 memset(dline_identical, 0, DOT_COUNT(state));
245 #endif
247 ret->recursion_remaining = state->recursion_depth;
248 ret->solver_status = SOLVER_INCOMPLETE;
250 ret->dotdsf = snewn(DOT_COUNT(state), int);
251 ret->looplen = snewn(DOT_COUNT(state), int);
252 for (i = 0; i < DOT_COUNT(state); i++) {
253 ret->dotdsf[i] = i;
254 ret->looplen[i] = 1;
257 return ret;
260 static void free_solver_state(solver_state *sstate) {
261 if (sstate) {
262 free_game(sstate->state);
263 sfree(sstate->dot_atleastone);
264 sfree(sstate->dot_atmostone);
265 /* sfree(sstate->dline_identical); */
266 sfree(sstate->dotdsf);
267 sfree(sstate->looplen);
268 sfree(sstate);
272 static solver_state *dup_solver_state(solver_state *sstate) {
273 game_state *state;
275 solver_state *ret = snew(solver_state);
277 ret->state = state = dup_game(sstate->state);
279 ret->dot_atmostone = snewn(DOT_COUNT(state), char);
280 memcpy(ret->dot_atmostone, sstate->dot_atmostone, DOT_COUNT(state));
282 ret->dot_atleastone = snewn(DOT_COUNT(state), char);
283 memcpy(ret->dot_atleastone, sstate->dot_atleastone, DOT_COUNT(state));
285 #if 0
286 ret->dline_identical = snewn((state->w + 1) * (state->h + 1), char);
287 memcpy(ret->dline_identical, state->dot_atmostone,
288 (state->w + 1) * (state->h + 1));
289 #endif
291 ret->recursion_remaining = sstate->recursion_remaining;
292 ret->solver_status = sstate->solver_status;
294 ret->dotdsf = snewn(DOT_COUNT(state), int);
295 ret->looplen = snewn(DOT_COUNT(state), int);
296 memcpy(ret->dotdsf, sstate->dotdsf, DOT_COUNT(state) * sizeof(int));
297 memcpy(ret->looplen, sstate->looplen, DOT_COUNT(state) * sizeof(int));
299 return ret;
303 * Merge two dots due to the existence of an edge between them.
304 * Updates the dsf tracking equivalence classes, and keeps track of
305 * the length of path each dot is currently a part of.
306 * Returns TRUE if the dots were already linked, ie if they are part of a
307 * closed loop, and false otherwise.
309 static int merge_dots(solver_state *sstate, int x1, int y1, int x2, int y2)
311 int i, j, len;
313 i = y1 * (sstate->state->w + 1) + x1;
314 j = y2 * (sstate->state->w + 1) + x2;
316 i = dsf_canonify(sstate->dotdsf, i);
317 j = dsf_canonify(sstate->dotdsf, j);
319 if (i == j) {
320 return TRUE;
321 } else {
322 len = sstate->looplen[i] + sstate->looplen[j];
323 dsf_merge(sstate->dotdsf, i, j);
324 i = dsf_canonify(sstate->dotdsf, i);
325 sstate->looplen[i] = len;
326 return FALSE;
330 /* Count the number of lines of a particular type currently going into the
331 * given dot. Lines going off the edge of the board are assumed fixed no. */
332 static int dot_order(const game_state* state, int i, int j, char line_type)
334 int n = 0;
336 if (i > 0) {
337 if (LEFTOF_DOT(state, i, j) == line_type)
338 ++n;
339 } else {
340 if (line_type == LINE_NO)
341 ++n;
343 if (i < state->w) {
344 if (RIGHTOF_DOT(state, i, j) == line_type)
345 ++n;
346 } else {
347 if (line_type == LINE_NO)
348 ++n;
350 if (j > 0) {
351 if (ABOVE_DOT(state, i, j) == line_type)
352 ++n;
353 } else {
354 if (line_type == LINE_NO)
355 ++n;
357 if (j < state->h) {
358 if (BELOW_DOT(state, i, j) == line_type)
359 ++n;
360 } else {
361 if (line_type == LINE_NO)
362 ++n;
365 return n;
367 /* Count the number of lines of a particular type currently surrounding the
368 * given square */
369 static int square_order(const game_state* state, int i, int j, char line_type)
371 int n = 0;
373 if (ABOVE_SQUARE(state, i, j) == line_type)
374 ++n;
375 if (BELOW_SQUARE(state, i, j) == line_type)
376 ++n;
377 if (LEFTOF_SQUARE(state, i, j) == line_type)
378 ++n;
379 if (RIGHTOF_SQUARE(state, i, j) == line_type)
380 ++n;
382 return n;
385 /* Set all lines bordering a dot of type old_type to type new_type
386 * Return value tells caller whether this function actually did anything */
387 static int dot_setall(game_state *state, int i, int j,
388 char old_type, char new_type)
390 int retval = FALSE;
391 if (old_type == new_type)
392 return FALSE;
394 if (i > 0 && LEFTOF_DOT(state, i, j) == old_type) {
395 LV_LEFTOF_DOT(state, i, j) = new_type;
396 retval = TRUE;
399 if (i < state->w && RIGHTOF_DOT(state, i, j) == old_type) {
400 LV_RIGHTOF_DOT(state, i, j) = new_type;
401 retval = TRUE;
404 if (j > 0 && ABOVE_DOT(state, i, j) == old_type) {
405 LV_ABOVE_DOT(state, i, j) = new_type;
406 retval = TRUE;
409 if (j < state->h && BELOW_DOT(state, i, j) == old_type) {
410 LV_BELOW_DOT(state, i, j) = new_type;
411 retval = TRUE;
414 return retval;
416 /* Set all lines bordering a square of type old_type to type new_type */
417 static void square_setall(game_state *state, int i, int j,
418 char old_type, char new_type)
420 if (ABOVE_SQUARE(state, i, j) == old_type)
421 ABOVE_SQUARE(state, i, j) = new_type;
422 if (BELOW_SQUARE(state, i, j) == old_type)
423 BELOW_SQUARE(state, i, j) = new_type;
424 if (LEFTOF_SQUARE(state, i, j) == old_type)
425 LEFTOF_SQUARE(state, i, j) = new_type;
426 if (RIGHTOF_SQUARE(state, i, j) == old_type)
427 RIGHTOF_SQUARE(state, i, j) = new_type;
430 static game_params *default_params(void)
432 game_params *ret = snew(game_params);
434 #ifdef SLOW_SYSTEM
435 ret->h = 4;
436 ret->w = 4;
437 #else
438 ret->h = 10;
439 ret->w = 10;
440 #endif
441 ret->diff = DIFF_EASY;
442 ret->rec = 0;
444 return ret;
447 static game_params *dup_params(game_params *params)
449 game_params *ret = snew(game_params);
450 *ret = *params; /* structure copy */
451 return ret;
454 static const struct {
455 char *desc;
456 game_params params;
457 } loopy_presets[] = {
458 { "4x4 Easy", { 4, 4, DIFF_EASY, 0 } },
459 { "4x4 Normal", { 4, 4, DIFF_NORMAL, 0 } },
460 { "7x7 Easy", { 7, 7, DIFF_EASY, 0 } },
461 { "7x7 Normal", { 7, 7, DIFF_NORMAL, 0 } },
462 { "10x10 Easy", { 10, 10, DIFF_EASY, 0 } },
463 { "10x10 Normal", { 10, 10, DIFF_NORMAL, 0 } },
464 #ifndef SLOW_SYSTEM
465 { "15x15 Easy", { 15, 15, DIFF_EASY, 0 } },
466 { "15x15 Normal", { 15, 15, DIFF_NORMAL, 0 } },
467 { "30x20 Easy", { 30, 20, DIFF_EASY, 0 } },
468 { "30x20 Normal", { 30, 20, DIFF_NORMAL, 0 } }
469 #endif
472 static int game_fetch_preset(int i, char **name, game_params **params)
474 game_params tmppar;
476 if (i < 0 || i >= lenof(loopy_presets))
477 return FALSE;
479 tmppar = loopy_presets[i].params;
480 *params = dup_params(&tmppar);
481 *name = dupstr(loopy_presets[i].desc);
483 return TRUE;
486 static void free_params(game_params *params)
488 sfree(params);
491 static void decode_params(game_params *params, char const *string)
493 params->h = params->w = atoi(string);
494 params->rec = 0;
495 params->diff = DIFF_EASY;
496 while (*string && isdigit((unsigned char)*string)) string++;
497 if (*string == 'x') {
498 string++;
499 params->h = atoi(string);
500 while (*string && isdigit((unsigned char)*string)) string++;
502 if (*string == 'r') {
503 string++;
504 params->rec = atoi(string);
505 while (*string && isdigit((unsigned char)*string)) string++;
507 if (*string == 'd') {
508 int i;
510 string++;
511 for (i = 0; i < DIFFCOUNT; i++)
512 if (*string == loopy_diffchars[i])
513 params->diff = i;
514 if (*string) string++;
518 static char *encode_params(game_params *params, int full)
520 char str[80];
521 sprintf(str, "%dx%d", params->w, params->h);
522 if (full)
523 sprintf(str + strlen(str), "r%dd%c", params->rec,
524 loopy_diffchars[params->diff]);
525 return dupstr(str);
528 static config_item *game_configure(game_params *params)
530 config_item *ret;
531 char buf[80];
533 ret = snewn(4, config_item);
535 ret[0].name = "Width";
536 ret[0].type = C_STRING;
537 sprintf(buf, "%d", params->w);
538 ret[0].sval = dupstr(buf);
539 ret[0].ival = 0;
541 ret[1].name = "Height";
542 ret[1].type = C_STRING;
543 sprintf(buf, "%d", params->h);
544 ret[1].sval = dupstr(buf);
545 ret[1].ival = 0;
547 ret[2].name = "Difficulty";
548 ret[2].type = C_CHOICES;
549 ret[2].sval = DIFFCONFIG;
550 ret[2].ival = params->diff;
552 ret[3].name = NULL;
553 ret[3].type = C_END;
554 ret[3].sval = NULL;
555 ret[3].ival = 0;
557 return ret;
560 static game_params *custom_params(config_item *cfg)
562 game_params *ret = snew(game_params);
564 ret->w = atoi(cfg[0].sval);
565 ret->h = atoi(cfg[1].sval);
566 ret->rec = 0;
567 ret->diff = cfg[2].ival;
569 return ret;
572 static char *validate_params(game_params *params, int full)
574 if (params->w < 4 || params->h < 4)
575 return "Width and height must both be at least 4";
576 if (params->rec < 0)
577 return "Recursion depth can't be negative";
580 * This shouldn't be able to happen at all, since decode_params
581 * and custom_params will never generate anything that isn't
582 * within range.
584 assert(params->diff >= 0 && params->diff < DIFFCOUNT);
586 return NULL;
589 /* We're going to store a list of current candidate squares for lighting.
590 * Each square gets a 'score', which tells us how adding that square right
591 * now would affect the length of the solution loop. We're trying to
592 * maximise that quantity so will bias our random selection of squares to
593 * light towards those with high scores */
594 struct square {
595 int score;
596 unsigned long random;
597 int x, y;
600 static int get_square_cmpfn(void *v1, void *v2)
602 struct square *s1 = (struct square *)v1;
603 struct square *s2 = (struct square *)v2;
604 int r;
606 r = s1->x - s2->x;
607 if (r)
608 return r;
610 r = s1->y - s2->y;
611 if (r)
612 return r;
614 return 0;
617 static int square_sort_cmpfn(void *v1, void *v2)
619 struct square *s1 = (struct square *)v1;
620 struct square *s2 = (struct square *)v2;
621 int r;
623 r = s2->score - s1->score;
624 if (r) {
625 return r;
628 if (s1->random < s2->random)
629 return -1;
630 else if (s1->random > s2->random)
631 return 1;
634 * It's _just_ possible that two squares might have been given
635 * the same random value. In that situation, fall back to
636 * comparing based on the coordinates. This introduces a tiny
637 * directional bias, but not a significant one.
639 return get_square_cmpfn(v1, v2);
642 static void print_tree(tree234 *tree)
644 #if 0
645 int i = 0;
646 struct square *s;
647 printf("Print tree:\n");
648 while (i < count234(tree)) {
649 s = (struct square *)index234(tree, i);
650 assert(s);
651 printf(" [%d,%d], %d, %d\n", s->x, s->y, s->score, s->random);
652 ++i;
654 #endif
657 enum { SQUARE_LIT, SQUARE_UNLIT };
659 #define SQUARE_STATE(i, j) \
660 (((i) < 0 || (i) >= params->w || \
661 (j) < 0 || (j) >= params->h) ? \
662 SQUARE_UNLIT : LV_SQUARE_STATE(i,j))
664 #define LV_SQUARE_STATE(i, j) board[(i) + params->w * (j)]
666 static void print_board(const game_params *params, const char *board)
668 #if 0
669 int i,j;
671 printf(" ");
672 for (i = 0; i < params->w; i++) {
673 printf("%d", i%10);
675 printf("\n");
676 for (j = 0; j < params->h; j++) {
677 printf("%d", j%10);
678 for (i = 0; i < params->w; i++) {
679 printf("%c", SQUARE_STATE(i, j) ? ' ' : 'O');
681 printf("\n");
683 #endif
686 static void add_full_clues(game_state *state, game_params *params,
687 random_state *rs)
689 char *clues;
690 char *board;
691 int i, j, a, b, c;
692 int board_area = SQUARE_COUNT(params);
693 int t;
695 struct square *square, *tmpsquare, *sq;
696 struct square square_pos;
698 /* These will contain exactly the same information, sorted into different
699 * orders */
700 tree234 *lightable_squares_sorted, *lightable_squares_gettable;
702 #define SQUARE_REACHABLE(i,j) \
703 (t = (SQUARE_STATE(i-1, j) == SQUARE_LIT || \
704 SQUARE_STATE(i+1, j) == SQUARE_LIT || \
705 SQUARE_STATE(i, j-1) == SQUARE_LIT || \
706 SQUARE_STATE(i, j+1) == SQUARE_LIT), \
707 /* printf("SQUARE_REACHABLE(%d,%d) = %d\n", i, j, t), */ \
711 /* One situation in which we may not light a square is if that'll leave one
712 * square above/below and one left/right of us unlit, separated by a lit
713 * square diagnonal from us */
714 #define SQUARE_DIAGONAL_VIOLATION(i, j, h, v) \
715 (t = (SQUARE_STATE((i)+(h), (j)) == SQUARE_UNLIT && \
716 SQUARE_STATE((i), (j)+(v)) == SQUARE_UNLIT && \
717 SQUARE_STATE((i)+(h), (j)+(v)) == SQUARE_LIT), \
718 /* t ? printf("SQUARE_DIAGONAL_VIOLATION(%d, %d, %d, %d)\n",
719 i, j, h, v) : 0,*/ \
722 /* We also may not light a square if it will form a loop of lit squares
723 * around some unlit squares, as then the game soln won't have a single
724 * loop */
725 #define SQUARE_LOOP_VIOLATION(i, j, lit1, lit2) \
726 (SQUARE_STATE((i)+1, (j)) == lit1 && \
727 SQUARE_STATE((i)-1, (j)) == lit1 && \
728 SQUARE_STATE((i), (j)+1) == lit2 && \
729 SQUARE_STATE((i), (j)-1) == lit2)
731 #define CAN_LIGHT_SQUARE(i, j) \
732 (SQUARE_REACHABLE(i, j) && \
733 !SQUARE_DIAGONAL_VIOLATION(i, j, -1, -1) && \
734 !SQUARE_DIAGONAL_VIOLATION(i, j, +1, -1) && \
735 !SQUARE_DIAGONAL_VIOLATION(i, j, -1, +1) && \
736 !SQUARE_DIAGONAL_VIOLATION(i, j, +1, +1) && \
737 !SQUARE_LOOP_VIOLATION(i, j, SQUARE_LIT, SQUARE_UNLIT) && \
738 !SQUARE_LOOP_VIOLATION(i, j, SQUARE_UNLIT, SQUARE_LIT))
740 #define IS_LIGHTING_CANDIDATE(i, j) \
741 (SQUARE_STATE(i, j) == SQUARE_UNLIT && \
742 CAN_LIGHT_SQUARE(i,j))
744 /* The 'score' of a square reflects its current desirability for selection
745 * as the next square to light. We want to encourage moving into uncharted
746 * areas so we give scores according to how many of the square's neighbours
747 * are currently unlit. */
749 /* UNLIT SCORE
750 * 3 2
751 * 2 0
752 * 1 -2
754 #define SQUARE_SCORE(i,j) \
755 (2*((SQUARE_STATE(i-1, j) == SQUARE_UNLIT) + \
756 (SQUARE_STATE(i+1, j) == SQUARE_UNLIT) + \
757 (SQUARE_STATE(i, j-1) == SQUARE_UNLIT) + \
758 (SQUARE_STATE(i, j+1) == SQUARE_UNLIT)) - 4)
760 /* When a square gets lit, this defines how far away from that square we
761 * need to go recomputing scores */
762 #define SCORE_DISTANCE 1
764 board = snewn(board_area, char);
765 clues = state->clues;
767 /* Make a board */
768 memset(board, SQUARE_UNLIT, board_area);
770 /* Seed the board with a single lit square near the middle */
771 i = params->w / 2;
772 j = params->h / 2;
773 if (params->w & 1 && random_bits(rs, 1))
774 ++i;
775 if (params->h & 1 && random_bits(rs, 1))
776 ++j;
778 LV_SQUARE_STATE(i, j) = SQUARE_LIT;
780 /* We need a way of favouring squares that will increase our loopiness.
781 * We do this by maintaining a list of all candidate squares sorted by
782 * their score and choose randomly from that with appropriate skew.
783 * In order to avoid consistently biasing towards particular squares, we
784 * need the sort order _within_ each group of scores to be completely
785 * random. But it would be abusing the hospitality of the tree234 data
786 * structure if our comparison function were nondeterministic :-). So with
787 * each square we associate a random number that does not change during a
788 * particular run of the generator, and use that as a secondary sort key.
789 * Yes, this means we will be biased towards particular random squares in
790 * any one run but that doesn't actually matter. */
792 lightable_squares_sorted = newtree234(square_sort_cmpfn);
793 lightable_squares_gettable = newtree234(get_square_cmpfn);
794 #define ADD_SQUARE(s) \
795 do { \
796 /* printf("ADD SQUARE: [%d,%d], %d, %d\n",
797 s->x, s->y, s->score, s->random);*/ \
798 sq = add234(lightable_squares_sorted, s); \
799 assert(sq == s); \
800 sq = add234(lightable_squares_gettable, s); \
801 assert(sq == s); \
802 } while (0)
804 #define REMOVE_SQUARE(s) \
805 do { \
806 /* printf("DELETE SQUARE: [%d,%d], %d, %d\n",
807 s->x, s->y, s->score, s->random);*/ \
808 sq = del234(lightable_squares_sorted, s); \
809 assert(sq); \
810 sq = del234(lightable_squares_gettable, s); \
811 assert(sq); \
812 } while (0)
814 #define HANDLE_DIR(a, b) \
815 square = snew(struct square); \
816 square->x = (i)+(a); \
817 square->y = (j)+(b); \
818 square->score = 2; \
819 square->random = random_bits(rs, 31); \
820 ADD_SQUARE(square);
821 HANDLE_DIR(-1, 0);
822 HANDLE_DIR( 1, 0);
823 HANDLE_DIR( 0,-1);
824 HANDLE_DIR( 0, 1);
825 #undef HANDLE_DIR
827 /* Light squares one at a time until the board is interesting enough */
828 while (TRUE)
830 /* We have count234(lightable_squares) possibilities, and in
831 * lightable_squares_sorted they are sorted with the most desirable
832 * first. */
833 c = count234(lightable_squares_sorted);
834 if (c == 0)
835 break;
836 assert(c == count234(lightable_squares_gettable));
838 /* Check that the best square available is any good */
839 square = (struct square *)index234(lightable_squares_sorted, 0);
840 assert(square);
843 * We never want to _decrease_ the loop's perimeter. Making
844 * moves that leave the perimeter the same is occasionally
845 * useful: if it were _never_ done then the user would be
846 * able to deduce illicitly that any degree-zero vertex was
847 * on the outside of the loop. So we do it sometimes but
848 * not always.
850 if (square->score < 0 || (square->score == 0 &&
851 random_upto(rs, 2) == 0))
852 break;
854 print_tree(lightable_squares_sorted);
855 assert(square->score == SQUARE_SCORE(square->x, square->y));
856 assert(SQUARE_STATE(square->x, square->y) == SQUARE_UNLIT);
857 assert(square->x >= 0 && square->x < params->w);
858 assert(square->y >= 0 && square->y < params->h);
859 /* printf("LIGHT SQUARE: [%d,%d], score = %d\n", square->x, square->y, square->score); */
861 /* Update data structures */
862 LV_SQUARE_STATE(square->x, square->y) = SQUARE_LIT;
863 REMOVE_SQUARE(square);
865 print_board(params, board);
867 /* We might have changed the score of any squares up to 2 units away in
868 * any direction */
869 for (b = -SCORE_DISTANCE; b <= SCORE_DISTANCE; b++) {
870 for (a = -SCORE_DISTANCE; a <= SCORE_DISTANCE; a++) {
871 if (!a && !b)
872 continue;
873 square_pos.x = square->x + a;
874 square_pos.y = square->y + b;
875 /* printf("Refreshing score for [%d,%d]:\n", square_pos.x, square_pos.y); */
876 if (square_pos.x < 0 || square_pos.x >= params->w ||
877 square_pos.y < 0 || square_pos.y >= params->h) {
878 /* printf(" Out of bounds\n"); */
879 continue;
881 tmpsquare = find234(lightable_squares_gettable, &square_pos,
882 NULL);
883 if (tmpsquare) {
884 /* printf(" Removing\n"); */
885 assert(tmpsquare->x == square_pos.x);
886 assert(tmpsquare->y == square_pos.y);
887 assert(SQUARE_STATE(tmpsquare->x, tmpsquare->y) ==
888 SQUARE_UNLIT);
889 REMOVE_SQUARE(tmpsquare);
890 } else {
891 /* printf(" Creating\n"); */
892 tmpsquare = snew(struct square);
893 tmpsquare->x = square_pos.x;
894 tmpsquare->y = square_pos.y;
895 tmpsquare->random = random_bits(rs, 31);
897 tmpsquare->score = SQUARE_SCORE(tmpsquare->x, tmpsquare->y);
899 if (IS_LIGHTING_CANDIDATE(tmpsquare->x, tmpsquare->y)) {
900 /* printf(" Adding\n"); */
901 ADD_SQUARE(tmpsquare);
902 } else {
903 /* printf(" Destroying\n"); */
904 sfree(tmpsquare);
908 sfree(square);
909 /* printf("\n\n"); */
912 while ((square = delpos234(lightable_squares_gettable, 0)) != NULL)
913 sfree(square);
914 freetree234(lightable_squares_gettable);
915 freetree234(lightable_squares_sorted);
917 /* Copy out all the clues */
918 for (j = 0; j < params->h; ++j) {
919 for (i = 0; i < params->w; ++i) {
920 c = SQUARE_STATE(i, j);
921 LV_CLUE_AT(state, i, j) = '0';
922 if (SQUARE_STATE(i-1, j) != c) ++LV_CLUE_AT(state, i, j);
923 if (SQUARE_STATE(i+1, j) != c) ++LV_CLUE_AT(state, i, j);
924 if (SQUARE_STATE(i, j-1) != c) ++LV_CLUE_AT(state, i, j);
925 if (SQUARE_STATE(i, j+1) != c) ++LV_CLUE_AT(state, i, j);
929 sfree(board);
932 static solver_state *solve_game_rec(const solver_state *sstate, int diff);
934 static int game_has_unique_soln(const game_state *state, int diff)
936 int ret;
937 solver_state *sstate_new;
938 solver_state *sstate = new_solver_state((game_state *)state);
940 sstate_new = solve_game_rec(sstate, diff);
942 ret = (sstate_new->solver_status == SOLVER_SOLVED);
944 free_solver_state(sstate_new);
945 free_solver_state(sstate);
947 return ret;
950 /* Remove clues one at a time at random. */
951 static game_state *remove_clues(game_state *state, random_state *rs, int diff)
953 int *square_list, squares;
954 game_state *ret = dup_game(state), *saved_ret;
955 int n;
957 /* We need to remove some clues. We'll do this by forming a list of all
958 * available equivalence classes, shuffling it, then going along one at a
959 * time clearing every member of each equivalence class, where removing a
960 * class doesn't render the board unsolvable. */
961 squares = state->w * state->h;
962 square_list = snewn(squares, int);
963 for (n = 0; n < squares; ++n) {
964 square_list[n] = n;
967 shuffle(square_list, squares, sizeof(int), rs);
969 for (n = 0; n < squares; ++n) {
970 saved_ret = dup_game(ret);
971 LV_CLUE_AT(ret, square_list[n] % state->w,
972 square_list[n] / state->w) = ' ';
973 if (game_has_unique_soln(ret, diff)) {
974 free_game(saved_ret);
975 } else {
976 free_game(ret);
977 ret = saved_ret;
980 sfree(square_list);
982 return ret;
985 static char *validate_desc(game_params *params, char *desc);
987 static char *new_game_desc(game_params *params, random_state *rs,
988 char **aux, int interactive)
990 /* solution and description both use run-length encoding in obvious ways */
991 char *retval;
992 char *description = snewn(SQUARE_COUNT(params) + 1, char);
993 char *dp = description;
994 int i, j;
995 int empty_count;
996 game_state *state = snew(game_state), *state_new;
998 state->h = params->h;
999 state->w = params->w;
1001 state->clues = snewn(SQUARE_COUNT(params), char);
1002 state->hl = snewn(HL_COUNT(params), char);
1003 state->vl = snewn(VL_COUNT(params), char);
1005 newboard_please:
1006 memset(state->hl, LINE_UNKNOWN, HL_COUNT(params));
1007 memset(state->vl, LINE_UNKNOWN, VL_COUNT(params));
1009 state->solved = state->cheated = FALSE;
1010 state->recursion_depth = params->rec;
1012 /* Get a new random solvable board with all its clues filled in. Yes, this
1013 * can loop for ever if the params are suitably unfavourable, but
1014 * preventing games smaller than 4x4 seems to stop this happening */
1016 do {
1017 add_full_clues(state, params, rs);
1018 } while (!game_has_unique_soln(state, params->diff));
1020 state_new = remove_clues(state, rs, params->diff);
1021 free_game(state);
1022 state = state_new;
1024 if (params->diff > 0 && game_has_unique_soln(state, params->diff-1)) {
1025 /* Board is too easy */
1026 goto newboard_please;
1029 empty_count = 0;
1030 for (j = 0; j < params->h; ++j) {
1031 for (i = 0; i < params->w; ++i) {
1032 if (CLUE_AT(state, i, j) == ' ') {
1033 if (empty_count > 25) {
1034 dp += sprintf(dp, "%c", (int)(empty_count + 'a' - 1));
1035 empty_count = 0;
1037 empty_count++;
1038 } else {
1039 if (empty_count) {
1040 dp += sprintf(dp, "%c", (int)(empty_count + 'a' - 1));
1041 empty_count = 0;
1043 dp += sprintf(dp, "%c", (int)(CLUE_AT(state, i, j)));
1047 if (empty_count)
1048 dp += sprintf(dp, "%c", (int)(empty_count + 'a' - 1));
1050 free_game(state);
1051 retval = dupstr(description);
1052 sfree(description);
1054 assert(!validate_desc(params, retval));
1056 return retval;
1059 /* We require that the params pass the test in validate_params and that the
1060 * description fills the entire game area */
1061 static char *validate_desc(game_params *params, char *desc)
1063 int count = 0;
1065 for (; *desc; ++desc) {
1066 if (*desc >= '0' && *desc <= '9') {
1067 count++;
1068 continue;
1070 if (*desc >= 'a') {
1071 count += *desc - 'a' + 1;
1072 continue;
1074 return "Unknown character in description";
1077 if (count < SQUARE_COUNT(params))
1078 return "Description too short for board size";
1079 if (count > SQUARE_COUNT(params))
1080 return "Description too long for board size";
1082 return NULL;
1085 static game_state *new_game(midend *me, game_params *params, char *desc)
1087 int i,j;
1088 game_state *state = snew(game_state);
1089 int empties_to_make = 0;
1090 int n;
1091 const char *dp = desc;
1093 state->recursion_depth = 0; /* XXX pending removal, probably */
1095 state->h = params->h;
1096 state->w = params->w;
1098 state->clues = snewn(SQUARE_COUNT(params), char);
1099 state->hl = snewn(HL_COUNT(params), char);
1100 state->vl = snewn(VL_COUNT(params), char);
1102 state->solved = state->cheated = FALSE;
1104 for (j = 0 ; j < params->h; ++j) {
1105 for (i = 0 ; i < params->w; ++i) {
1106 if (empties_to_make) {
1107 empties_to_make--;
1108 LV_CLUE_AT(state, i, j) = ' ';
1109 continue;
1112 assert(*dp);
1113 n = *dp - '0';
1114 if (n >=0 && n < 10) {
1115 LV_CLUE_AT(state, i, j) = *dp;
1116 } else {
1117 n = *dp - 'a' + 1;
1118 assert(n > 0);
1119 LV_CLUE_AT(state, i, j) = ' ';
1120 empties_to_make = n - 1;
1122 ++dp;
1126 memset(state->hl, LINE_UNKNOWN, HL_COUNT(params));
1127 memset(state->vl, LINE_UNKNOWN, VL_COUNT(params));
1129 return state;
1132 enum { LOOP_NONE=0, LOOP_SOLN, LOOP_NOT_SOLN };
1134 /* Sums the lengths of the numbers in range [0,n) */
1135 /* See equivalent function in solo.c for justification of this. */
1136 static int len_0_to_n(int n)
1138 int len = 1; /* Counting 0 as a bit of a special case */
1139 int i;
1141 for (i = 1; i < n; i *= 10) {
1142 len += max(n - i, 0);
1145 return len;
1148 static char *encode_solve_move(const game_state *state)
1150 int len, i, j;
1151 char *ret, *p;
1152 /* This is going to return a string representing the moves needed to set
1153 * every line in a grid to be the same as the ones in 'state'. The exact
1154 * length of this string is predictable. */
1156 len = 1; /* Count the 'S' prefix */
1157 /* Numbers in horizontal lines */
1158 /* Horizontal lines, x position */
1159 len += len_0_to_n(state->w) * (state->h + 1);
1160 /* Horizontal lines, y position */
1161 len += len_0_to_n(state->h + 1) * (state->w);
1162 /* Vertical lines, y position */
1163 len += len_0_to_n(state->h) * (state->w + 1);
1164 /* Vertical lines, x position */
1165 len += len_0_to_n(state->w + 1) * (state->h);
1166 /* For each line we also have two letters and a comma */
1167 len += 3 * (HL_COUNT(state) + VL_COUNT(state));
1169 ret = snewn(len + 1, char);
1170 p = ret;
1172 p += sprintf(p, "S");
1174 for (j = 0; j < state->h + 1; ++j) {
1175 for (i = 0; i < state->w; ++i) {
1176 switch (RIGHTOF_DOT(state, i, j)) {
1177 case LINE_YES:
1178 p += sprintf(p, "%d,%dhy", i, j);
1179 break;
1180 case LINE_NO:
1181 p += sprintf(p, "%d,%dhn", i, j);
1182 break;
1183 /* default: */
1184 /* I'm going to forgive this because I think the results
1185 * are cute. */
1186 /* assert(!"Solver produced incomplete solution!"); */
1191 for (j = 0; j < state->h; ++j) {
1192 for (i = 0; i < state->w + 1; ++i) {
1193 switch (BELOW_DOT(state, i, j)) {
1194 case LINE_YES:
1195 p += sprintf(p, "%d,%dvy", i, j);
1196 break;
1197 case LINE_NO:
1198 p += sprintf(p, "%d,%dvn", i, j);
1199 break;
1200 /* default: */
1201 /* I'm going to forgive this because I think the results
1202 * are cute. */
1203 /* assert(!"Solver produced incomplete solution!"); */
1209 * Ensure we haven't overrun the buffer we allocated (which we
1210 * really shouldn't have, since we computed its maximum size).
1211 * Note that this assert is <= rather than ==, because the
1212 * solver is permitted to produce an incomplete solution in
1213 * which case the buffer will be only partially used.
1215 assert(strlen(ret) <= (size_t)len);
1216 return ret;
1219 /* BEGIN SOLVER IMPLEMENTATION */
1221 /* For each pair of lines through each dot we store a bit for whether
1222 * exactly one of those lines is ON, and in separate arrays we store whether
1223 * at least one is on and whether at most 1 is on. (If we know both or
1224 * neither is on that's already stored more directly.) That's six bits per
1225 * dot. Bit number n represents the lines shown in dot_type_dirs[n]. */
1227 enum dline {
1228 DLINE_VERT = 0,
1229 DLINE_HORIZ = 1,
1230 DLINE_UL = 2,
1231 DLINE_DR = 3,
1232 DLINE_UR = 4,
1233 DLINE_DL = 5
1236 #define OPP_DLINE(dline) (dline ^ 1)
1239 #define SQUARE_DLINES \
1240 HANDLE_DLINE(DLINE_UL, RIGHTOF_SQUARE, BELOW_SQUARE, 1, 1); \
1241 HANDLE_DLINE(DLINE_UR, LEFTOF_SQUARE, BELOW_SQUARE, 0, 1); \
1242 HANDLE_DLINE(DLINE_DL, RIGHTOF_SQUARE, ABOVE_SQUARE, 1, 0); \
1243 HANDLE_DLINE(DLINE_DR, LEFTOF_SQUARE, ABOVE_SQUARE, 0, 0);
1245 #define DOT_DLINES \
1246 HANDLE_DLINE(DLINE_VERT, ABOVE_DOT, BELOW_DOT); \
1247 HANDLE_DLINE(DLINE_HORIZ, LEFTOF_DOT, RIGHTOF_DOT); \
1248 HANDLE_DLINE(DLINE_UL, ABOVE_DOT, LEFTOF_DOT); \
1249 HANDLE_DLINE(DLINE_UR, ABOVE_DOT, RIGHTOF_DOT); \
1250 HANDLE_DLINE(DLINE_DL, BELOW_DOT, LEFTOF_DOT); \
1251 HANDLE_DLINE(DLINE_DR, BELOW_DOT, RIGHTOF_DOT);
1253 static void array_setall(char *array, char from, char to, int len)
1255 char *p = array, *p_old = p;
1256 int len_remaining = len;
1258 while ((p = memchr(p, from, len_remaining))) {
1259 *p = to;
1260 len_remaining -= p - p_old;
1261 p_old = p;
1265 static int dot_setall_dlines(solver_state *sstate, enum dline dl, int i, int j,
1266 enum line_state line_old, enum line_state line_new)
1268 game_state *state = sstate->state;
1269 int retval = FALSE;
1271 if (line_old == line_new)
1272 return FALSE;
1274 /* First line in dline */
1275 switch (dl) {
1276 case DLINE_UL:
1277 case DLINE_UR:
1278 case DLINE_VERT:
1279 if (j > 0 && ABOVE_DOT(state, i, j) == line_old) {
1280 LV_ABOVE_DOT(state, i, j) = line_new;
1281 retval = TRUE;
1283 break;
1284 case DLINE_DL:
1285 case DLINE_DR:
1286 if (j < (state)->h && BELOW_DOT(state, i, j) == line_old) {
1287 LV_BELOW_DOT(state, i, j) = line_new;
1288 retval = TRUE;
1290 break;
1291 case DLINE_HORIZ:
1292 if (i > 0 && LEFTOF_DOT(state, i, j) == line_old) {
1293 LV_LEFTOF_DOT(state, i, j) = line_new;
1294 retval = TRUE;
1296 break;
1299 /* Second line in dline */
1300 switch (dl) {
1301 case DLINE_UL:
1302 case DLINE_DL:
1303 if (i > 0 && LEFTOF_DOT(state, i, j) == line_old) {
1304 LV_LEFTOF_DOT(state, i, j) = line_new;
1305 retval = TRUE;
1307 break;
1308 case DLINE_UR:
1309 case DLINE_DR:
1310 case DLINE_HORIZ:
1311 if (i < (state)->w && RIGHTOF_DOT(state, i, j) == line_old) {
1312 LV_RIGHTOF_DOT(state, i, j) = line_new;
1313 retval = TRUE;
1315 break;
1316 case DLINE_VERT:
1317 if (j < (state)->h && BELOW_DOT(state, i, j) == line_old) {
1318 LV_BELOW_DOT(state, i, j) = line_new;
1319 retval = TRUE;
1321 break;
1324 return retval;
1327 #if 0
1328 /* This will fail an assertion if {dx,dy} are anything other than {-1,0}, {1,0}
1329 * {0,-1} or {0,1} */
1330 static int line_status_from_point(const game_state *state,
1331 int x, int y, int dx, int dy)
1333 if (dx == -1 && dy == 0)
1334 return LEFTOF_DOT(state, x, y);
1335 if (dx == 1 && dy == 0)
1336 return RIGHTOF_DOT(state, x, y);
1337 if (dx == 0 && dy == -1)
1338 return ABOVE_DOT(state, x, y);
1339 if (dx == 0 && dy == 1)
1340 return BELOW_DOT(state, x, y);
1342 assert(!"Illegal dx or dy in line_status_from_point");
1343 return 0;
1345 #endif
1347 /* This will return a dynamically allocated solver_state containing the (more)
1348 * solved grid */
1349 static solver_state *solve_game_rec(const solver_state *sstate_start, int diff)
1351 int i, j, w, h;
1352 int current_yes, current_no, desired;
1353 solver_state *sstate, *sstate_saved, *sstate_tmp;
1354 int t;
1355 solver_state *sstate_rec_solved;
1356 int recursive_soln_count;
1357 char *square_solved;
1358 char *dot_solved;
1359 int solver_progress;
1361 h = sstate_start->state->h;
1362 w = sstate_start->state->w;
1364 dot_solved = snewn(DOT_COUNT(sstate_start->state), char);
1365 square_solved = snewn(SQUARE_COUNT(sstate_start->state), char);
1366 memset(dot_solved, FALSE, DOT_COUNT(sstate_start->state));
1367 memset(square_solved, FALSE, SQUARE_COUNT(sstate_start->state));
1369 #if 0
1370 printf("solve_game_rec: recursion_remaining = %d\n",
1371 sstate_start->recursion_remaining);
1372 #endif
1374 sstate = dup_solver_state((solver_state *)sstate_start);
1376 #define FOUND_MISTAKE \
1377 do { \
1378 sstate->solver_status = SOLVER_MISTAKE; \
1379 sfree(dot_solved); sfree(square_solved); \
1380 free_solver_state(sstate_saved); \
1381 return sstate; \
1382 } while (0)
1384 sstate_saved = NULL;
1386 nonrecursive_solver:
1388 while (1) {
1389 solver_progress = FALSE;
1391 /* First we do the 'easy' work, that might cause concrete results */
1393 /* Per-square deductions */
1394 for (j = 0; j < h; ++j) {
1395 for (i = 0; i < w; ++i) {
1396 /* Begin rules that look at the clue (if there is one) */
1397 if (square_solved[i + j*w])
1398 continue;
1400 desired = CLUE_AT(sstate->state, i, j);
1401 if (desired == ' ')
1402 continue;
1404 desired = desired - '0';
1405 current_yes = square_order(sstate->state, i, j, LINE_YES);
1406 current_no = square_order(sstate->state, i, j, LINE_NO);
1408 if (current_yes + current_no == 4) {
1409 square_solved[i + j*w] = TRUE;
1410 continue;
1413 if (desired < current_yes)
1414 FOUND_MISTAKE;
1415 if (desired == current_yes) {
1416 square_setall(sstate->state, i, j, LINE_UNKNOWN, LINE_NO);
1417 square_solved[i + j*w] = TRUE;
1418 solver_progress = TRUE;
1419 continue;
1422 if (4 - desired < current_no)
1423 FOUND_MISTAKE;
1424 if (4 - desired == current_no) {
1425 square_setall(sstate->state, i, j, LINE_UNKNOWN, LINE_YES);
1426 square_solved[i + j*w] = TRUE;
1427 solver_progress = TRUE;
1432 /* Per-dot deductions */
1433 for (j = 0; j < h + 1; ++j) {
1434 for (i = 0; i < w + 1; ++i) {
1435 if (dot_solved[i + j*(w+1)])
1436 continue;
1438 switch (dot_order(sstate->state, i, j, LINE_YES)) {
1439 case 0:
1440 switch (dot_order(sstate->state, i, j, LINE_NO)) {
1441 case 3:
1442 dot_setall(sstate->state, i, j, LINE_UNKNOWN, LINE_NO);
1443 solver_progress = TRUE;
1444 /* fall through */
1445 case 4:
1446 dot_solved[i + j*(w+1)] = TRUE;
1447 break;
1449 break;
1450 case 1:
1451 switch (dot_order(sstate->state, i, j, LINE_NO)) {
1452 #define H1(dline, dir1_dot, dir2_dot, dot_howmany) \
1453 if (dir1_dot(sstate->state, i, j) == LINE_UNKNOWN) { \
1454 if (dir2_dot(sstate->state, i, j) == LINE_UNKNOWN){ \
1455 solver_progress |= \
1456 SET_BIT(sstate->dot_howmany[i + (w + 1) * j], \
1457 dline); \
1460 case 1:
1461 if (diff > DIFF_EASY) {
1462 #define HANDLE_DLINE(dline, dir1_dot, dir2_dot) \
1463 H1(dline, dir1_dot, dir2_dot, dot_atleastone)
1464 /* 1 yes, 1 no, so exactly one of unknowns is
1465 * yes */
1466 DOT_DLINES;
1467 #undef HANDLE_DLINE
1469 /* fall through */
1470 case 0:
1471 if (diff > DIFF_EASY) {
1472 #define HANDLE_DLINE(dline, dir1_dot, dir2_dot) \
1473 H1(dline, dir1_dot, dir2_dot, dot_atmostone)
1474 /* 1 yes, fewer than 2 no, so at most one of
1475 * unknowns is yes */
1476 DOT_DLINES;
1477 #undef HANDLE_DLINE
1479 #undef H1
1480 break;
1481 case 2: /* 1 yes, 2 no */
1482 dot_setall(sstate->state, i, j,
1483 LINE_UNKNOWN, LINE_YES);
1484 dot_solved[i + j*(w+1)] = TRUE;
1485 solver_progress = TRUE;
1486 break;
1487 case 3: /* 1 yes, 3 no */
1488 FOUND_MISTAKE;
1489 break;
1491 break;
1492 case 2:
1493 if (dot_setall(sstate->state, i, j, LINE_UNKNOWN, LINE_NO)) {
1494 solver_progress = TRUE;
1496 dot_solved[i + j*(w+1)] = TRUE;
1497 break;
1498 case 3:
1499 case 4:
1500 FOUND_MISTAKE;
1501 break;
1503 if (diff > DIFF_EASY) {
1504 #define HANDLE_DLINE(dline, dir1_dot, dir2_dot) \
1505 if (BIT_SET(sstate->dot_atleastone[i + (w + 1) * j], dline)) { \
1506 solver_progress |= \
1507 SET_BIT(sstate->dot_atmostone[i + (w + 1) * j], \
1508 OPP_DLINE(dline)); \
1510 /* If at least one of a dline in a dot is YES, at most one
1511 * of the opposite dline to that dot must be YES. */
1512 DOT_DLINES;
1514 #undef HANDLE_DLINE
1516 #define H1(dline, dir1_sq, dir2_sq, dot_howmany, line_query, line_set) \
1517 if (BIT_SET(sstate->dot_howmany[i + (w+1) * j], dline)) { \
1518 t = dir1_sq(sstate->state, i, j); \
1519 if (t == line_query) { \
1520 if (dir2_sq(sstate->state, i, j) != line_set) { \
1521 LV_##dir2_sq(sstate->state, i, j) = line_set; \
1522 solver_progress = TRUE; \
1524 } else { \
1525 t = dir2_sq(sstate->state, i, j); \
1526 if (t == line_query) { \
1527 if (dir1_sq(sstate->state, i, j) != line_set) { \
1528 LV_##dir1_sq(sstate->state, i, j) = line_set; \
1529 solver_progress = TRUE; \
1534 if (diff > DIFF_EASY) {
1535 #define HANDLE_DLINE(dline, dir1_sq, dir2_sq) \
1536 H1(dline, dir1_sq, dir2_sq, dot_atmostone, LINE_YES, LINE_NO)
1537 /* If at most one of the DLINE is on, and one is definitely
1538 * on, set the other to definitely off */
1539 DOT_DLINES;
1540 #undef HANDLE_DLINE
1543 if (diff > DIFF_EASY) {
1544 #define HANDLE_DLINE(dline, dir1_sq, dir2_sq) \
1545 H1(dline, dir1_sq, dir2_sq, dot_atleastone, LINE_NO, LINE_YES)
1546 /* If at least one of the DLINE is on, and one is definitely
1547 * off, set the other to definitely on */
1548 DOT_DLINES;
1549 #undef HANDLE_DLINE
1551 #undef H1
1556 /* More obscure per-square operations */
1557 for (j = 0; j < h; ++j) {
1558 for (i = 0; i < w; ++i) {
1559 if (square_solved[i + j*w])
1560 continue;
1562 switch (CLUE_AT(sstate->state, i, j)) {
1563 case '1':
1564 if (diff > DIFF_EASY) {
1565 #define HANDLE_DLINE(dline, dir1_sq, dir2_sq, a, b) \
1566 /* At most one of any DLINE can be set */ \
1567 SET_BIT(sstate->dot_atmostone[i+a + (w + 1) * (j+b)], \
1568 dline); \
1569 /* This DLINE provides enough YESes to solve the clue */\
1570 if (BIT_SET(sstate->dot_atleastone \
1571 [i+a + (w + 1) * (j+b)], \
1572 dline)) { \
1573 solver_progress |= \
1574 dot_setall_dlines(sstate, OPP_DLINE(dline), \
1575 i+(1-a), j+(1-b), \
1576 LINE_UNKNOWN, LINE_NO); \
1578 SQUARE_DLINES;
1579 #undef HANDLE_DLINE
1581 break;
1582 case '2':
1583 if (diff > DIFF_EASY) {
1584 #define H1(dline, dot_at1one, dot_at2one, a, b) \
1585 if (BIT_SET(sstate->dot_at1one \
1586 [i+a + (w+1) * (j+b)], dline)) { \
1587 solver_progress |= \
1588 SET_BIT(sstate->dot_at2one \
1589 [i+(1-a) + (w+1) * (j+(1-b))], \
1590 OPP_DLINE(dline)); \
1592 #define HANDLE_DLINE(dline, dir1_sq, dir2_sq, a, b) \
1593 H1(dline, dot_atleastone, dot_atmostone, a, b); \
1594 H1(dline, dot_atmostone, dot_atleastone, a, b);
1595 /* If at least one of one DLINE is set, at most one
1596 * of the opposing one is and vice versa */
1597 SQUARE_DLINES;
1599 #undef HANDLE_DLINE
1600 #undef H1
1601 break;
1602 case '3':
1603 if (diff > DIFF_EASY) {
1604 #define HANDLE_DLINE(dline, dir1_sq, dir2_sq, a, b) \
1605 /* At least one of any DLINE can be set */ \
1606 solver_progress |= \
1607 SET_BIT(sstate->dot_atleastone \
1608 [i+a + (w + 1) * (j+b)], \
1609 dline); \
1610 /* This DLINE provides enough NOs to solve the clue */ \
1611 if (BIT_SET(sstate->dot_atmostone \
1612 [i+a + (w + 1) * (j+b)], \
1613 dline)) { \
1614 solver_progress |= \
1615 dot_setall_dlines(sstate, OPP_DLINE(dline), \
1616 i+(1-a), j+(1-b), \
1617 LINE_UNKNOWN, LINE_YES); \
1619 SQUARE_DLINES;
1620 #undef HANDLE_DLINE
1622 break;
1627 if (!solver_progress) {
1628 int edgecount = 0, clues = 0, satclues = 0, sm1clues = 0;
1629 int shortest_chainlen = DOT_COUNT(sstate->state);
1630 int loop_found = FALSE;
1631 int d;
1632 int dots_connected;
1635 * Go through the grid and update for all the new edges.
1636 * Since merge_dots() is idempotent, the simplest way to
1637 * do this is just to update for _all_ the edges.
1639 * Also, while we're here, we count the edges, count the
1640 * clues, count the satisfied clues, and count the
1641 * satisfied-minus-one clues.
1643 for (j = 0; j < h+1; ++j) {
1644 for (i = 0; i < w+1; ++i) {
1645 if (RIGHTOF_DOT(sstate->state, i, j) == LINE_YES) {
1646 loop_found |= merge_dots(sstate, i, j, i+1, j);
1647 edgecount++;
1649 if (BELOW_DOT(sstate->state, i, j) == LINE_YES) {
1650 loop_found |= merge_dots(sstate, i, j, i, j+1);
1651 edgecount++;
1654 if (CLUE_AT(sstate->state, i, j) != ' ') {
1655 int c = CLUE_AT(sstate->state, i, j) - '0';
1656 int o = square_order(sstate->state, i, j, LINE_YES);
1657 if (o == c)
1658 satclues++;
1659 else if (o == c-1)
1660 sm1clues++;
1661 clues++;
1666 for (i = 0; i < DOT_COUNT(sstate->state); ++i) {
1667 dots_connected = sstate->looplen[dsf_canonify(sstate->dotdsf,i)];
1668 if (dots_connected > 1)
1669 shortest_chainlen = min(shortest_chainlen, dots_connected);
1672 assert(sstate->solver_status == SOLVER_INCOMPLETE);
1674 if (satclues == clues && shortest_chainlen == edgecount) {
1675 sstate->solver_status = SOLVER_SOLVED;
1676 /* This discovery clearly counts as progress, even if we haven't
1677 * just added any lines or anything */
1678 solver_progress = TRUE;
1679 goto finished_loop_checking;
1683 * Now go through looking for LINE_UNKNOWN edges which
1684 * connect two dots that are already in the same
1685 * equivalence class. If we find one, test to see if the
1686 * loop it would create is a solution.
1688 for (j = 0; j <= h; ++j) {
1689 for (i = 0; i <= w; ++i) {
1690 for (d = 0; d < 2; d++) {
1691 int i2, j2, eqclass, val;
1693 if (d == 0) {
1694 if (RIGHTOF_DOT(sstate->state, i, j) !=
1695 LINE_UNKNOWN)
1696 continue;
1697 i2 = i+1;
1698 j2 = j;
1699 } else {
1700 if (BELOW_DOT(sstate->state, i, j) !=
1701 LINE_UNKNOWN)
1702 continue;
1703 i2 = i;
1704 j2 = j+1;
1707 eqclass = dsf_canonify(sstate->dotdsf, j * (w+1) + i);
1708 if (eqclass != dsf_canonify(sstate->dotdsf,
1709 j2 * (w+1) + i2))
1710 continue;
1712 val = LINE_NO; /* loop is bad until proven otherwise */
1715 * This edge would form a loop. Next
1716 * question: how long would the loop be?
1717 * Would it equal the total number of edges
1718 * (plus the one we'd be adding if we added
1719 * it)?
1721 if (sstate->looplen[eqclass] == edgecount + 1) {
1722 int sm1_nearby;
1723 int cx, cy;
1726 * This edge would form a loop which
1727 * took in all the edges in the entire
1728 * grid. So now we need to work out
1729 * whether it would be a valid solution
1730 * to the puzzle, which means we have to
1731 * check if it satisfies all the clues.
1732 * This means that every clue must be
1733 * either satisfied or satisfied-minus-
1734 * 1, and also that the number of
1735 * satisfied-minus-1 clues must be at
1736 * most two and they must lie on either
1737 * side of this edge.
1739 sm1_nearby = 0;
1740 cx = i - (j2-j);
1741 cy = j - (i2-i);
1742 if (CLUE_AT(sstate->state, cx,cy) != ' ' &&
1743 square_order(sstate->state, cx,cy, LINE_YES) ==
1744 CLUE_AT(sstate->state, cx,cy) - '0' - 1)
1745 sm1_nearby++;
1746 if (CLUE_AT(sstate->state, i, j) != ' ' &&
1747 square_order(sstate->state, i, j, LINE_YES) ==
1748 CLUE_AT(sstate->state, i, j) - '0' - 1)
1749 sm1_nearby++;
1750 if (sm1clues == sm1_nearby &&
1751 sm1clues + satclues == clues)
1752 val = LINE_YES; /* loop is good! */
1756 * Right. Now we know that adding this edge
1757 * would form a loop, and we know whether
1758 * that loop would be a viable solution or
1759 * not.
1761 * If adding this edge produces a solution,
1762 * then we know we've found _a_ solution but
1763 * we don't know that it's _the_ solution -
1764 * if it were provably the solution then
1765 * we'd have deduced this edge some time ago
1766 * without the need to do loop detection. So
1767 * in this state we return SOLVER_AMBIGUOUS,
1768 * which has the effect that hitting Solve
1769 * on a user-provided puzzle will fill in a
1770 * solution but using the solver to
1771 * construct new puzzles won't consider this
1772 * a reasonable deduction for the user to
1773 * make.
1775 if (d == 0) {
1776 LV_RIGHTOF_DOT(sstate->state, i, j) = val;
1777 solver_progress = TRUE;
1778 } else {
1779 LV_BELOW_DOT(sstate->state, i, j) = val;
1780 solver_progress = TRUE;
1782 if (val == LINE_YES) {
1783 sstate->solver_status = SOLVER_AMBIGUOUS;
1784 goto finished_loop_checking;
1790 finished_loop_checking:
1792 if (!solver_progress ||
1793 sstate->solver_status == SOLVER_SOLVED ||
1794 sstate->solver_status == SOLVER_AMBIGUOUS) {
1795 break;
1800 sfree(dot_solved); sfree(square_solved);
1802 if (sstate->solver_status == SOLVER_SOLVED ||
1803 sstate->solver_status == SOLVER_AMBIGUOUS) {
1804 /* s/LINE_UNKNOWN/LINE_NO/g */
1805 array_setall(sstate->state->hl, LINE_UNKNOWN, LINE_NO,
1806 HL_COUNT(sstate->state));
1807 array_setall(sstate->state->vl, LINE_UNKNOWN, LINE_NO,
1808 VL_COUNT(sstate->state));
1809 return sstate;
1812 /* Perform recursive calls */
1813 if (sstate->recursion_remaining) {
1814 sstate_saved = dup_solver_state(sstate);
1816 sstate->recursion_remaining--;
1818 recursive_soln_count = 0;
1819 sstate_rec_solved = NULL;
1821 /* Memory management:
1822 * sstate_saved won't be modified but needs to be freed when we have
1823 * finished with it.
1824 * sstate is expected to contain our 'best' solution by the time we
1825 * finish this section of code. It's the thing we'll try adding lines
1826 * to, seeing if they make it more solvable.
1827 * If sstate_rec_solved is non-NULL, it will supersede sstate
1828 * eventually. sstate_tmp should not hold a value persistently.
1831 /* NB SOLVER_AMBIGUOUS is like SOLVER_SOLVED except the solver is aware
1832 * of the possibility of additional solutions. So as soon as we have a
1833 * SOLVER_AMBIGUOUS we can safely propagate it back to our caller, but
1834 * if we get a SOLVER_SOLVED we want to keep trying in case we find
1835 * further solutions and have to mark it ambiguous.
1838 #define DO_RECURSIVE_CALL(dir_dot) \
1839 if (dir_dot(sstate->state, i, j) == LINE_UNKNOWN) { \
1840 debug(("Trying " #dir_dot " at [%d,%d]\n", i, j)); \
1841 LV_##dir_dot(sstate->state, i, j) = LINE_YES; \
1842 sstate_tmp = solve_game_rec(sstate, diff); \
1843 switch (sstate_tmp->solver_status) { \
1844 case SOLVER_AMBIGUOUS: \
1845 debug(("Solver ambiguous, returning\n")); \
1846 sstate_rec_solved = sstate_tmp; \
1847 goto finished_recursion; \
1848 case SOLVER_SOLVED: \
1849 switch (++recursive_soln_count) { \
1850 case 1: \
1851 debug(("One solution found\n")); \
1852 sstate_rec_solved = sstate_tmp; \
1853 break; \
1854 case 2: \
1855 debug(("Ambiguous solutions found\n")); \
1856 free_solver_state(sstate_tmp); \
1857 sstate_rec_solved->solver_status = SOLVER_AMBIGUOUS;\
1858 goto finished_recursion; \
1859 default: \
1860 assert(!"recursive_soln_count out of range"); \
1861 break; \
1863 break; \
1864 case SOLVER_MISTAKE: \
1865 debug(("Non-solution found\n")); \
1866 free_solver_state(sstate_tmp); \
1867 free_solver_state(sstate_saved); \
1868 LV_##dir_dot(sstate->state, i, j) = LINE_NO; \
1869 goto nonrecursive_solver; \
1870 case SOLVER_INCOMPLETE: \
1871 debug(("Recursive step inconclusive\n")); \
1872 free_solver_state(sstate_tmp); \
1873 break; \
1875 free_solver_state(sstate); \
1876 sstate = dup_solver_state(sstate_saved); \
1879 for (j = 0; j < h + 1; ++j) {
1880 for (i = 0; i < w + 1; ++i) {
1881 /* Only perform recursive calls on 'loose ends' */
1882 if (dot_order(sstate->state, i, j, LINE_YES) == 1) {
1883 DO_RECURSIVE_CALL(LEFTOF_DOT);
1884 DO_RECURSIVE_CALL(RIGHTOF_DOT);
1885 DO_RECURSIVE_CALL(ABOVE_DOT);
1886 DO_RECURSIVE_CALL(BELOW_DOT);
1891 finished_recursion:
1893 if (sstate_rec_solved) {
1894 free_solver_state(sstate);
1895 sstate = sstate_rec_solved;
1899 return sstate;
1902 /* XXX bits of solver that may come in handy one day */
1903 #if 0
1904 #define HANDLE_DLINE(dline, dir1_dot, dir2_dot) \
1905 /* dline from this dot that's entirely unknown must have
1906 * both lines identical */ \
1907 if (dir1_dot(sstate->state, i, j) == LINE_UNKNOWN && \
1908 dir2_dot(sstate->state, i, j) == LINE_UNKNOWN) { \
1909 sstate->dline_identical[i + (sstate->state->w + 1) * j] |= \
1910 1<<dline; \
1911 } else if (sstate->dline_identical[i +
1912 (sstate->state->w + 1) * j] &\
1913 1<<dline) { \
1914 /* If they're identical and one is known do the obvious
1915 * thing */ \
1916 t = dir1_dot(sstate->state, i, j); \
1917 if (t != LINE_UNKNOWN) \
1918 dir2_dot(sstate->state, i, j) = t; \
1919 else { \
1920 t = dir2_dot(sstate->state, i, j); \
1921 if (t != LINE_UNKNOWN) \
1922 dir1_dot(sstate->state, i, j) = t; \
1925 DOT_DLINES;
1926 #undef HANDLE_DLINE
1927 #endif
1929 #if 0
1930 #define HANDLE_DLINE(dline, dir1_sq, dir2_sq, a, b) \
1931 if (sstate->dline_identical[i+a + \
1932 (sstate->state->w + 1) * (j+b)] &\
1933 1<<dline) { \
1934 dir1_sq(sstate->state, i, j) = LINE_YES; \
1935 dir2_sq(sstate->state, i, j) = LINE_YES; \
1937 /* If two lines are the same they must be on */
1938 SQUARE_DLINES;
1939 #undef HANDLE_DLINE
1940 #endif
1943 #if 0
1944 #define HANDLE_DLINE(dline, dir1_sq, dir2_sq, a, b) \
1945 if (sstate->dot_atmostone[i+a + (sstate->state->w + 1) * (j+b)] & \
1946 1<<dline) { \
1947 if (square_order(sstate->state, i, j, LINE_UNKNOWN) - 1 == \
1948 CLUE_AT(sstate->state, i, j) - '0') { \
1949 square_setall(sstate->state, i, j, LINE_UNKNOWN, LINE_YES); \
1950 /* XXX the following may overwrite known data! */ \
1951 dir1_sq(sstate->state, i, j) = LINE_UNKNOWN; \
1952 dir2_sq(sstate->state, i, j) = LINE_UNKNOWN; \
1955 SQUARE_DLINES;
1956 #undef HANDLE_DLINE
1957 #endif
1959 #if 0
1960 #define HANDLE_DLINE(dline, dir1_sq, dir2_sq, a, b) \
1961 if (sstate->dline_identical[i+a +
1962 (sstate->state->w + 1) * (j+b)] &\
1963 1<<dline) { \
1964 dir1_sq(sstate->state, i, j) = LINE_NO; \
1965 dir2_sq(sstate->state, i, j) = LINE_NO; \
1967 /* If two lines are the same they must be off */
1968 SQUARE_DLINES;
1969 #undef HANDLE_DLINE
1970 #endif
1972 static char *solve_game(game_state *state, game_state *currstate,
1973 char *aux, char **error)
1975 char *soln = NULL;
1976 solver_state *sstate, *new_sstate;
1978 sstate = new_solver_state(state);
1979 new_sstate = solve_game_rec(sstate, DIFFCOUNT);
1981 if (new_sstate->solver_status == SOLVER_SOLVED) {
1982 soln = encode_solve_move(new_sstate->state);
1983 } else if (new_sstate->solver_status == SOLVER_AMBIGUOUS) {
1984 soln = encode_solve_move(new_sstate->state);
1985 /**error = "Solver found ambiguous solutions"; */
1986 } else {
1987 soln = encode_solve_move(new_sstate->state);
1988 /**error = "Solver failed"; */
1991 free_solver_state(new_sstate);
1992 free_solver_state(sstate);
1994 return soln;
1997 static char *game_text_format(game_state *state)
1999 int i, j;
2000 int len;
2001 char *ret, *rp;
2003 len = (2 * state->w + 2) * (2 * state->h + 1);
2004 rp = ret = snewn(len + 1, char);
2006 #define DRAW_HL \
2007 switch (ABOVE_SQUARE(state, i, j)) { \
2008 case LINE_YES: \
2009 rp += sprintf(rp, " -"); \
2010 break; \
2011 case LINE_NO: \
2012 rp += sprintf(rp, " x"); \
2013 break; \
2014 case LINE_UNKNOWN: \
2015 rp += sprintf(rp, " "); \
2016 break; \
2017 default: \
2018 assert(!"Illegal line state for HL");\
2021 #define DRAW_VL \
2022 switch (LEFTOF_SQUARE(state, i, j)) {\
2023 case LINE_YES: \
2024 rp += sprintf(rp, "|"); \
2025 break; \
2026 case LINE_NO: \
2027 rp += sprintf(rp, "x"); \
2028 break; \
2029 case LINE_UNKNOWN: \
2030 rp += sprintf(rp, " "); \
2031 break; \
2032 default: \
2033 assert(!"Illegal line state for VL");\
2036 for (j = 0; j < state->h; ++j) {
2037 for (i = 0; i < state->w; ++i) {
2038 DRAW_HL;
2040 rp += sprintf(rp, " \n");
2041 for (i = 0; i < state->w; ++i) {
2042 DRAW_VL;
2043 rp += sprintf(rp, "%c", (int)(CLUE_AT(state, i, j)));
2045 DRAW_VL;
2046 rp += sprintf(rp, "\n");
2048 for (i = 0; i < state->w; ++i) {
2049 DRAW_HL;
2051 rp += sprintf(rp, " \n");
2053 assert(strlen(ret) == len);
2054 return ret;
2057 static game_ui *new_ui(game_state *state)
2059 return NULL;
2062 static void free_ui(game_ui *ui)
2066 static char *encode_ui(game_ui *ui)
2068 return NULL;
2071 static void decode_ui(game_ui *ui, char *encoding)
2075 static void game_changed_state(game_ui *ui, game_state *oldstate,
2076 game_state *newstate)
2080 struct game_drawstate {
2081 int started;
2082 int tilesize, linewidth;
2083 int flashing;
2084 char *hl, *vl;
2085 char *clue_error;
2088 static char *interpret_move(game_state *state, game_ui *ui, game_drawstate *ds,
2089 int x, int y, int button)
2091 int hl_selected;
2092 int i, j, p, q;
2093 char *ret, buf[80];
2094 char button_char = ' ';
2095 enum line_state old_state;
2097 button &= ~MOD_MASK;
2099 /* Around each line is a diamond-shaped region where points within that
2100 * region are closer to this line than any other. We assume any click
2101 * within a line's diamond was meant for that line. It would all be a lot
2102 * simpler if the / and % operators respected modulo arithmetic properly
2103 * for negative numbers. */
2105 x -= BORDER;
2106 y -= BORDER;
2108 /* Get the coordinates of the square the click was in */
2109 i = (x + TILE_SIZE) / TILE_SIZE - 1;
2110 j = (y + TILE_SIZE) / TILE_SIZE - 1;
2112 /* Get the precise position inside square [i,j] */
2113 p = (x + TILE_SIZE) % TILE_SIZE;
2114 q = (y + TILE_SIZE) % TILE_SIZE;
2116 /* After this bit of magic [i,j] will correspond to the point either above
2117 * or to the left of the line selected */
2118 if (p > q) {
2119 if (TILE_SIZE - p > q) {
2120 hl_selected = TRUE;
2121 } else {
2122 hl_selected = FALSE;
2123 ++i;
2125 } else {
2126 if (TILE_SIZE - q > p) {
2127 hl_selected = FALSE;
2128 } else {
2129 hl_selected = TRUE;
2130 ++j;
2134 if (i < 0 || j < 0)
2135 return NULL;
2137 if (hl_selected) {
2138 if (i >= state->w || j >= state->h + 1)
2139 return NULL;
2140 } else {
2141 if (i >= state->w + 1 || j >= state->h)
2142 return NULL;
2145 /* I think it's only possible to play this game with mouse clicks, sorry */
2146 /* Maybe will add mouse drag support some time */
2147 if (hl_selected)
2148 old_state = RIGHTOF_DOT(state, i, j);
2149 else
2150 old_state = BELOW_DOT(state, i, j);
2152 switch (button) {
2153 case LEFT_BUTTON:
2154 switch (old_state) {
2155 case LINE_UNKNOWN:
2156 button_char = 'y';
2157 break;
2158 case LINE_YES:
2159 case LINE_NO:
2160 button_char = 'u';
2161 break;
2163 break;
2164 case MIDDLE_BUTTON:
2165 button_char = 'u';
2166 break;
2167 case RIGHT_BUTTON:
2168 switch (old_state) {
2169 case LINE_UNKNOWN:
2170 button_char = 'n';
2171 break;
2172 case LINE_NO:
2173 case LINE_YES:
2174 button_char = 'u';
2175 break;
2177 break;
2178 default:
2179 return NULL;
2183 sprintf(buf, "%d,%d%c%c", i, j, (int)(hl_selected ? 'h' : 'v'), (int)button_char);
2184 ret = dupstr(buf);
2186 return ret;
2189 static game_state *execute_move(game_state *state, char *move)
2191 int i, j;
2192 game_state *newstate = dup_game(state);
2194 if (move[0] == 'S') {
2195 move++;
2196 newstate->cheated = TRUE;
2199 while (*move) {
2200 i = atoi(move);
2201 move = strchr(move, ',');
2202 if (!move)
2203 goto fail;
2204 j = atoi(++move);
2205 move += strspn(move, "1234567890");
2206 switch (*(move++)) {
2207 case 'h':
2208 if (i >= newstate->w || j > newstate->h)
2209 goto fail;
2210 switch (*(move++)) {
2211 case 'y':
2212 LV_RIGHTOF_DOT(newstate, i, j) = LINE_YES;
2213 break;
2214 case 'n':
2215 LV_RIGHTOF_DOT(newstate, i, j) = LINE_NO;
2216 break;
2217 case 'u':
2218 LV_RIGHTOF_DOT(newstate, i, j) = LINE_UNKNOWN;
2219 break;
2220 default:
2221 goto fail;
2223 break;
2224 case 'v':
2225 if (i > newstate->w || j >= newstate->h)
2226 goto fail;
2227 switch (*(move++)) {
2228 case 'y':
2229 LV_BELOW_DOT(newstate, i, j) = LINE_YES;
2230 break;
2231 case 'n':
2232 LV_BELOW_DOT(newstate, i, j) = LINE_NO;
2233 break;
2234 case 'u':
2235 LV_BELOW_DOT(newstate, i, j) = LINE_UNKNOWN;
2236 break;
2237 default:
2238 goto fail;
2240 break;
2241 default:
2242 goto fail;
2247 * Check for completion.
2249 i = 0; /* placate optimiser */
2250 for (j = 0; j <= newstate->h; j++) {
2251 for (i = 0; i < newstate->w; i++)
2252 if (LV_RIGHTOF_DOT(newstate, i, j) == LINE_YES)
2253 break;
2254 if (i < newstate->w)
2255 break;
2257 if (j <= newstate->h) {
2258 int prevdir = 'R';
2259 int x = i, y = j;
2260 int looplen, count;
2263 * We've found a horizontal edge at (i,j). Follow it round
2264 * to see if it's part of a loop.
2266 looplen = 0;
2267 while (1) {
2268 int order = dot_order(newstate, x, y, LINE_YES);
2269 if (order != 2)
2270 goto completion_check_done;
2272 if (LEFTOF_DOT(newstate, x, y) == LINE_YES && prevdir != 'L') {
2273 x--;
2274 prevdir = 'R';
2275 } else if (RIGHTOF_DOT(newstate, x, y) == LINE_YES &&
2276 prevdir != 'R') {
2277 x++;
2278 prevdir = 'L';
2279 } else if (ABOVE_DOT(newstate, x, y) == LINE_YES &&
2280 prevdir != 'U') {
2281 y--;
2282 prevdir = 'D';
2283 } else if (BELOW_DOT(newstate, x, y) == LINE_YES &&
2284 prevdir != 'D') {
2285 y++;
2286 prevdir = 'U';
2287 } else {
2288 assert(!"Can't happen"); /* dot_order guarantees success */
2291 looplen++;
2293 if (x == i && y == j)
2294 break;
2297 if (x != i || y != j || looplen == 0)
2298 goto completion_check_done;
2301 * We've traced our way round a loop, and we know how many
2302 * line segments were involved. Count _all_ the line
2303 * segments in the grid, to see if the loop includes them
2304 * all.
2306 count = 0;
2307 for (j = 0; j <= newstate->h; j++)
2308 for (i = 0; i <= newstate->w; i++)
2309 count += ((RIGHTOF_DOT(newstate, i, j) == LINE_YES) +
2310 (BELOW_DOT(newstate, i, j) == LINE_YES));
2311 assert(count >= looplen);
2312 if (count != looplen)
2313 goto completion_check_done;
2316 * The grid contains one closed loop and nothing else.
2317 * Check that all the clues are satisfied.
2319 for (j = 0; j < newstate->h; ++j) {
2320 for (i = 0; i < newstate->w; ++i) {
2321 int n = CLUE_AT(newstate, i, j);
2322 if (n != ' ') {
2323 if (square_order(newstate, i, j, LINE_YES) != n - '0') {
2324 goto completion_check_done;
2331 * Completed!
2333 newstate->solved = TRUE;
2336 completion_check_done:
2337 return newstate;
2339 fail:
2340 free_game(newstate);
2341 return NULL;
2344 /* ----------------------------------------------------------------------
2345 * Drawing routines.
2348 #define SIZE(d) ((d) * TILE_SIZE + 2 * BORDER + 1)
2350 static void game_compute_size(game_params *params, int tilesize,
2351 int *x, int *y)
2353 struct { int tilesize; } ads, *ds = &ads;
2354 ads.tilesize = tilesize;
2356 *x = SIZE(params->w);
2357 *y = SIZE(params->h);
2360 static void game_set_size(drawing *dr, game_drawstate *ds,
2361 game_params *params, int tilesize)
2363 ds->tilesize = tilesize;
2364 ds->linewidth = max(1,tilesize/16);
2367 static float *game_colours(frontend *fe, int *ncolours)
2369 float *ret = snewn(4 * NCOLOURS, float);
2371 frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
2373 ret[COL_FOREGROUND * 3 + 0] = 0.0F;
2374 ret[COL_FOREGROUND * 3 + 1] = 0.0F;
2375 ret[COL_FOREGROUND * 3 + 2] = 0.0F;
2377 ret[COL_HIGHLIGHT * 3 + 0] = 1.0F;
2378 ret[COL_HIGHLIGHT * 3 + 1] = 1.0F;
2379 ret[COL_HIGHLIGHT * 3 + 2] = 1.0F;
2381 ret[COL_MISTAKE * 3 + 0] = 1.0F;
2382 ret[COL_MISTAKE * 3 + 1] = 0.0F;
2383 ret[COL_MISTAKE * 3 + 2] = 0.0F;
2385 *ncolours = NCOLOURS;
2386 return ret;
2389 static game_drawstate *game_new_drawstate(drawing *dr, game_state *state)
2391 struct game_drawstate *ds = snew(struct game_drawstate);
2393 ds->tilesize = ds->linewidth = 0;
2394 ds->started = 0;
2395 ds->hl = snewn(HL_COUNT(state), char);
2396 ds->vl = snewn(VL_COUNT(state), char);
2397 ds->clue_error = snewn(SQUARE_COUNT(state), char);
2398 ds->flashing = 0;
2400 memset(ds->hl, LINE_UNKNOWN, HL_COUNT(state));
2401 memset(ds->vl, LINE_UNKNOWN, VL_COUNT(state));
2402 memset(ds->clue_error, 0, SQUARE_COUNT(state));
2404 return ds;
2407 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
2409 sfree(ds->clue_error);
2410 sfree(ds->hl);
2411 sfree(ds->vl);
2412 sfree(ds);
2415 static void game_redraw(drawing *dr, game_drawstate *ds, game_state *oldstate,
2416 game_state *state, int dir, game_ui *ui,
2417 float animtime, float flashtime)
2419 int i, j, n;
2420 int w = state->w, h = state->h;
2421 char c[2];
2422 int line_colour, flash_changed;
2423 int clue_mistake;
2425 if (!ds->started) {
2427 * The initial contents of the window are not guaranteed and
2428 * can vary with front ends. To be on the safe side, all games
2429 * should start by drawing a big background-colour rectangle
2430 * covering the whole window.
2432 draw_rect(dr, 0, 0, SIZE(state->w), SIZE(state->h), COL_BACKGROUND);
2434 /* Draw dots */
2435 for (j = 0; j < h + 1; ++j) {
2436 for (i = 0; i < w + 1; ++i) {
2437 draw_rect(dr,
2438 BORDER + i * TILE_SIZE - LINEWIDTH/2,
2439 BORDER + j * TILE_SIZE - LINEWIDTH/2,
2440 LINEWIDTH, LINEWIDTH, COL_FOREGROUND);
2444 /* Draw clues */
2445 for (j = 0; j < h; ++j) {
2446 for (i = 0; i < w; ++i) {
2447 c[0] = CLUE_AT(state, i, j);
2448 c[1] = '\0';
2449 draw_text(dr,
2450 BORDER + i * TILE_SIZE + TILE_SIZE/2,
2451 BORDER + j * TILE_SIZE + TILE_SIZE/2,
2452 FONT_VARIABLE, TILE_SIZE/2,
2453 ALIGN_VCENTRE | ALIGN_HCENTRE, COL_FOREGROUND, c);
2456 draw_update(dr, 0, 0,
2457 state->w * TILE_SIZE + 2*BORDER + 1,
2458 state->h * TILE_SIZE + 2*BORDER + 1);
2459 ds->started = TRUE;
2462 if (flashtime > 0 &&
2463 (flashtime <= FLASH_TIME/3 ||
2464 flashtime >= FLASH_TIME*2/3)) {
2465 flash_changed = !ds->flashing;
2466 ds->flashing = TRUE;
2467 line_colour = COL_HIGHLIGHT;
2468 } else {
2469 flash_changed = ds->flashing;
2470 ds->flashing = FALSE;
2471 line_colour = COL_FOREGROUND;
2474 #define CROSS_SIZE (3 * LINEWIDTH / 2)
2476 /* Redraw clue colours if necessary */
2477 for (j = 0; j < h; ++j) {
2478 for (i = 0; i < w; ++i) {
2479 c[0] = CLUE_AT(state, i, j);
2480 c[1] = '\0';
2481 if (c[0] == ' ')
2482 continue;
2484 n = c[0] - '0';
2485 assert(n >= 0 && n <= 4);
2487 clue_mistake = (square_order(state, i, j, LINE_YES) > n ||
2488 square_order(state, i, j, LINE_NO ) > (4-n));
2490 if (clue_mistake != ds->clue_error[j * w + i]) {
2491 draw_rect(dr,
2492 BORDER + i * TILE_SIZE + CROSS_SIZE,
2493 BORDER + j * TILE_SIZE + CROSS_SIZE,
2494 TILE_SIZE - CROSS_SIZE * 2, TILE_SIZE - CROSS_SIZE * 2,
2495 COL_BACKGROUND);
2496 draw_text(dr,
2497 BORDER + i * TILE_SIZE + TILE_SIZE/2,
2498 BORDER + j * TILE_SIZE + TILE_SIZE/2,
2499 FONT_VARIABLE, TILE_SIZE/2,
2500 ALIGN_VCENTRE | ALIGN_HCENTRE,
2501 clue_mistake ? COL_MISTAKE : COL_FOREGROUND, c);
2502 draw_update(dr, i * TILE_SIZE + BORDER, j * TILE_SIZE + BORDER,
2503 TILE_SIZE, TILE_SIZE);
2505 ds->clue_error[j * w + i] = clue_mistake;
2510 /* I've also had a request to colour lines red if they make a non-solution
2511 * loop, or if more than two lines go into any point. I think that would
2512 * be good some time. */
2514 #define CLEAR_VL(i, j) do { \
2515 draw_rect(dr, \
2516 BORDER + i * TILE_SIZE - CROSS_SIZE, \
2517 BORDER + j * TILE_SIZE + LINEWIDTH - LINEWIDTH/2, \
2518 CROSS_SIZE * 2, \
2519 TILE_SIZE - LINEWIDTH, \
2520 COL_BACKGROUND); \
2521 draw_update(dr, \
2522 BORDER + i * TILE_SIZE - CROSS_SIZE, \
2523 BORDER + j * TILE_SIZE - CROSS_SIZE, \
2524 CROSS_SIZE*2, \
2525 TILE_SIZE + CROSS_SIZE*2); \
2526 } while (0)
2528 #define CLEAR_HL(i, j) do { \
2529 draw_rect(dr, \
2530 BORDER + i * TILE_SIZE + LINEWIDTH - LINEWIDTH/2, \
2531 BORDER + j * TILE_SIZE - CROSS_SIZE, \
2532 TILE_SIZE - LINEWIDTH, \
2533 CROSS_SIZE * 2, \
2534 COL_BACKGROUND); \
2535 draw_update(dr, \
2536 BORDER + i * TILE_SIZE - CROSS_SIZE, \
2537 BORDER + j * TILE_SIZE - CROSS_SIZE, \
2538 TILE_SIZE + CROSS_SIZE*2, \
2539 CROSS_SIZE*2); \
2540 } while (0)
2542 /* Vertical lines */
2543 for (j = 0; j < h; ++j) {
2544 for (i = 0; i < w + 1; ++i) {
2545 switch (BELOW_DOT(state, i, j)) {
2546 case LINE_UNKNOWN:
2547 if (ds->vl[i + (w + 1) * j] != BELOW_DOT(state, i, j)) {
2548 CLEAR_VL(i, j);
2550 break;
2551 case LINE_YES:
2552 if (ds->vl[i + (w + 1) * j] != BELOW_DOT(state, i, j) ||
2553 flash_changed) {
2554 CLEAR_VL(i, j);
2555 draw_rect(dr,
2556 BORDER + i * TILE_SIZE - LINEWIDTH/2,
2557 BORDER + j * TILE_SIZE + LINEWIDTH - LINEWIDTH/2,
2558 LINEWIDTH, TILE_SIZE - LINEWIDTH,
2559 line_colour);
2561 break;
2562 case LINE_NO:
2563 if (ds->vl[i + (w + 1) * j] != BELOW_DOT(state, i, j)) {
2564 CLEAR_VL(i, j);
2565 draw_line(dr,
2566 BORDER + i * TILE_SIZE - CROSS_SIZE,
2567 BORDER + j * TILE_SIZE + TILE_SIZE/2 - CROSS_SIZE,
2568 BORDER + i * TILE_SIZE + CROSS_SIZE - 1,
2569 BORDER + j * TILE_SIZE + TILE_SIZE/2 + CROSS_SIZE - 1,
2570 COL_FOREGROUND);
2571 draw_line(dr,
2572 BORDER + i * TILE_SIZE + CROSS_SIZE - 1,
2573 BORDER + j * TILE_SIZE + TILE_SIZE/2 - CROSS_SIZE,
2574 BORDER + i * TILE_SIZE - CROSS_SIZE,
2575 BORDER + j * TILE_SIZE + TILE_SIZE/2 + CROSS_SIZE - 1,
2576 COL_FOREGROUND);
2578 break;
2580 ds->vl[i + (w + 1) * j] = BELOW_DOT(state, i, j);
2584 /* Horizontal lines */
2585 for (j = 0; j < h + 1; ++j) {
2586 for (i = 0; i < w; ++i) {
2587 switch (RIGHTOF_DOT(state, i, j)) {
2588 case LINE_UNKNOWN:
2589 if (ds->hl[i + w * j] != RIGHTOF_DOT(state, i, j)) {
2590 CLEAR_HL(i, j);
2592 break;
2593 case LINE_YES:
2594 if (ds->hl[i + w * j] != RIGHTOF_DOT(state, i, j) ||
2595 flash_changed) {
2596 CLEAR_HL(i, j);
2597 draw_rect(dr,
2598 BORDER + i * TILE_SIZE + LINEWIDTH - LINEWIDTH/2,
2599 BORDER + j * TILE_SIZE - LINEWIDTH/2,
2600 TILE_SIZE - LINEWIDTH, LINEWIDTH,
2601 line_colour);
2602 break;
2604 case LINE_NO:
2605 if (ds->hl[i + w * j] != RIGHTOF_DOT(state, i, j)) {
2606 CLEAR_HL(i, j);
2607 draw_line(dr,
2608 BORDER + i * TILE_SIZE + TILE_SIZE/2 - CROSS_SIZE,
2609 BORDER + j * TILE_SIZE + CROSS_SIZE - 1,
2610 BORDER + i * TILE_SIZE + TILE_SIZE/2 + CROSS_SIZE - 1,
2611 BORDER + j * TILE_SIZE - CROSS_SIZE,
2612 COL_FOREGROUND);
2613 draw_line(dr,
2614 BORDER + i * TILE_SIZE + TILE_SIZE/2 - CROSS_SIZE,
2615 BORDER + j * TILE_SIZE - CROSS_SIZE,
2616 BORDER + i * TILE_SIZE + TILE_SIZE/2 + CROSS_SIZE - 1,
2617 BORDER + j * TILE_SIZE + CROSS_SIZE - 1,
2618 COL_FOREGROUND);
2619 break;
2622 ds->hl[i + w * j] = RIGHTOF_DOT(state, i, j);
2627 static float game_anim_length(game_state *oldstate, game_state *newstate,
2628 int dir, game_ui *ui)
2630 return 0.0F;
2633 static float game_flash_length(game_state *oldstate, game_state *newstate,
2634 int dir, game_ui *ui)
2636 if (!oldstate->solved && newstate->solved &&
2637 !oldstate->cheated && !newstate->cheated) {
2638 return FLASH_TIME;
2641 return 0.0F;
2644 static int game_timing_state(game_state *state, game_ui *ui)
2646 return TRUE;
2649 static void game_print_size(game_params *params, float *x, float *y)
2651 int pw, ph;
2654 * I'll use 7mm squares by default.
2656 game_compute_size(params, 700, &pw, &ph);
2657 *x = pw / 100.0F;
2658 *y = ph / 100.0F;
2661 static void game_print(drawing *dr, game_state *state, int tilesize)
2663 int w = state->w, h = state->h;
2664 int ink = print_mono_colour(dr, 0);
2665 int x, y;
2666 game_drawstate ads, *ds = &ads;
2668 game_set_size(dr, ds, NULL, tilesize);
2671 * Dots. I'll deliberately make the dots a bit wider than the
2672 * lines, so you can still see them. (And also because it's
2673 * annoyingly tricky to make them _exactly_ the same size...)
2675 for (y = 0; y <= h; y++)
2676 for (x = 0; x <= w; x++)
2677 draw_circle(dr, BORDER + x * TILE_SIZE, BORDER + y * TILE_SIZE,
2678 LINEWIDTH, ink, ink);
2681 * Clues.
2683 for (y = 0; y < h; y++)
2684 for (x = 0; x < w; x++)
2685 if (CLUE_AT(state, x, y) != ' ') {
2686 char c[2];
2688 c[0] = CLUE_AT(state, x, y);
2689 c[1] = '\0';
2690 draw_text(dr,
2691 BORDER + x * TILE_SIZE + TILE_SIZE/2,
2692 BORDER + y * TILE_SIZE + TILE_SIZE/2,
2693 FONT_VARIABLE, TILE_SIZE/2,
2694 ALIGN_VCENTRE | ALIGN_HCENTRE, ink, c);
2698 * Lines. (At the moment, I'm not bothering with crosses.)
2700 for (y = 0; y <= h; y++)
2701 for (x = 0; x < w; x++)
2702 if (RIGHTOF_DOT(state, x, y) == LINE_YES)
2703 draw_rect(dr, BORDER + x * TILE_SIZE,
2704 BORDER + y * TILE_SIZE - LINEWIDTH/2,
2705 TILE_SIZE, (LINEWIDTH/2) * 2 + 1, ink);
2706 for (y = 0; y < h; y++)
2707 for (x = 0; x <= w; x++)
2708 if (BELOW_DOT(state, x, y) == LINE_YES)
2709 draw_rect(dr, BORDER + x * TILE_SIZE - LINEWIDTH/2,
2710 BORDER + y * TILE_SIZE,
2711 (LINEWIDTH/2) * 2 + 1, TILE_SIZE, ink);
2714 #ifdef COMBINED
2715 #define thegame loopy
2716 #endif
2718 const struct game thegame = {
2719 "Loopy", "loopy",
2720 default_params,
2721 game_fetch_preset,
2722 decode_params,
2723 encode_params,
2724 free_params,
2725 dup_params,
2726 TRUE, game_configure, custom_params,
2727 validate_params,
2728 new_game_desc,
2729 validate_desc,
2730 new_game,
2731 dup_game,
2732 free_game,
2733 1, solve_game,
2734 TRUE, game_text_format,
2735 new_ui,
2736 free_ui,
2737 encode_ui,
2738 decode_ui,
2739 game_changed_state,
2740 interpret_move,
2741 execute_move,
2742 PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
2743 game_colours,
2744 game_new_drawstate,
2745 game_free_drawstate,
2746 game_redraw,
2747 game_anim_length,
2748 game_flash_length,
2749 TRUE, FALSE, game_print_size, game_print,
2750 FALSE, /* wants_statusbar */
2751 FALSE, game_timing_state,
2752 0, /* flags */