2 * loopy.c: An implementation of the Nikoli game 'Loop the loop'.
3 * (c) Mike Pinna, 2005, 2006
5 * vim: set shiftwidth=4 :set textwidth=80:
11 * - Setting very high recursion depth seems to cause memory munching: are we
12 * recursing before checking completion, by any chance?
14 * - There's an interesting deductive technique which makes use of topology
15 * rather than just graph theory. Each _square_ in the grid is either inside
16 * or outside the loop; you can tell that two squares are on the same side
17 * of the loop if they're separated by an x (or, more generally, by a path
18 * crossing no LINE_UNKNOWNs and an even number of LINE_YESes), and on the
19 * opposite side of the loop if they're separated by a line (or an odd
20 * number of LINE_YESes and no LINE_UNKNOWNs). Oh, and any square separated
21 * from the outside of the grid by a LINE_YES or a LINE_NO is on the inside
22 * or outside respectively. So if you can track this for all squares, you
23 * figure out the state of the line between a pair once their relative
24 * insideness is known.
26 * - (Just a speed optimisation.) Consider some todo list queue where every
27 * time we modify something we mark it for consideration by other bits of
28 * the solver, to save iteration over things that have already been done.
41 /* Debugging options */
42 /*#define DEBUG_CACHES*/
43 /*#define SHOW_WORKING*/
45 /* ----------------------------------------------------------------------
46 * Struct, enum and function declarations
60 /* Put -1 in a square that doesn't get a clue */
63 /* Arrays of line states, stored left-to-right, top-to-bottom */
73 SOLVER_SOLVED, /* This is the only solution the solver could find */
74 SOLVER_MISTAKE, /* This is definitely not a solution */
75 SOLVER_AMBIGUOUS, /* This _might_ be an ambiguous solution */
76 SOLVER_INCOMPLETE /* This may be a partial solution */
79 typedef struct normal {
88 typedef struct solver_state {
90 int recursion_remaining;
91 enum solver_status solver_status;
92 /* NB looplen is the number of dots that are joined together at a point, ie a
93 * looplen of 1 means there are no lines to a particular dot */
99 char *square_yescount;
100 char *square_nocount;
101 char *dot_solved, *square_solved;
104 normal_mode_state *normal;
105 hard_mode_state *hard;
109 * Difficulty levels. I do some macro ickery here to ensure that my
110 * enum and the various forms of my name list always match up.
113 #define DIFFLIST(A) \
114 A(EASY,Easy,e,easy_mode_deductions) \
115 A(NORMAL,Normal,n,normal_mode_deductions) \
116 A(HARD,Hard,h,hard_mode_deductions)
117 #define ENUM(upper,title,lower,fn) DIFF_ ## upper,
118 #define TITLE(upper,title,lower,fn) #title,
119 #define ENCODE(upper,title,lower,fn) #lower
120 #define CONFIG(upper,title,lower,fn) ":" #title
121 #define SOLVER_FN_DECL(upper,title,lower,fn) static int fn(solver_state *);
122 #define SOLVER_FN(upper,title,lower,fn) &fn,
123 enum { DIFFLIST(ENUM) DIFF_MAX };
124 static char const *const diffnames[] = { DIFFLIST(TITLE) };
125 static char const diffchars[] = DIFFLIST(ENCODE);
126 #define DIFFCONFIG DIFFLIST(CONFIG)
127 DIFFLIST(SOLVER_FN_DECL);
128 static int (*(solver_fns[]))(solver_state *) = { DIFFLIST(SOLVER_FN) };
136 enum line_state { LINE_YES, LINE_UNKNOWN, LINE_NO };
141 enum direction { UP, LEFT, RIGHT, DOWN };
143 #define OPP_DIR(dir) \
146 struct game_drawstate {
148 int tilesize, linewidth;
154 static char *game_text_format(game_state *state);
155 static char *state_to_text(const game_state *state);
156 static char *validate_desc(game_params *params, char *desc);
157 static int get_line_status_from_point(const game_state *state,
158 int x, int y, enum direction d);
159 static int dot_order(const game_state* state, int i, int j, char line_type);
160 static int square_order(const game_state* state, int i, int j, char line_type);
161 static solver_state *solve_game_rec(const solver_state *sstate,
165 static void check_caches(const solver_state* sstate);
167 #define check_caches(s)
170 /* ----------------------------------------------------------------------
174 /* General constants */
175 #define PREFERRED_TILE_SIZE 32
176 #define TILE_SIZE (ds->tilesize)
177 #define LINEWIDTH (ds->linewidth)
178 #define BORDER (TILE_SIZE / 2)
179 #define FLASH_TIME 0.5F
181 /* Counts of various things that we're interested in */
182 #define HL_COUNT(state) ((state)->w * ((state)->h + 1))
183 #define VL_COUNT(state) (((state)->w + 1) * (state)->h)
184 #define LINE_COUNT(state) (HL_COUNT(state) + VL_COUNT(state))
185 #define DOT_COUNT(state) (((state)->w + 1) * ((state)->h + 1))
186 #define SQUARE_COUNT(state) ((state)->w * (state)->h)
188 /* For indexing into arrays */
189 #define DOT_INDEX(state, x, y) ((x) + ((state)->w + 1) * (y))
190 #define SQUARE_INDEX(state, x, y) ((x) + ((state)->w) * (y))
191 #define HL_INDEX(state, x, y) SQUARE_INDEX(state, x, y)
192 #define VL_INDEX(state, x, y) DOT_INDEX(state, x, y)
194 /* Useful utility functions */
195 #define LEGAL_DOT(state, i, j) ((i) >= 0 && (j) >= 0 && \
196 (i) <= (state)->w && (j) <= (state)->h)
197 #define LEGAL_SQUARE(state, i, j) ((i) >= 0 && (j) >= 0 && \
198 (i) < (state)->w && (j) < (state)->h)
200 #define CLUE_AT(state, i, j) (LEGAL_SQUARE(state, i, j) ? \
201 LV_CLUE_AT(state, i, j) : -1)
203 #define LV_CLUE_AT(state, i, j) ((state)->clues[SQUARE_INDEX(state, i, j)])
205 #define BIT_SET(field, bit) ((field) & (1<<(bit)))
207 #define SET_BIT(field, bit) (BIT_SET(field, bit) ? FALSE : \
208 ((field) |= (1<<(bit)), TRUE))
210 #define CLEAR_BIT(field, bit) (BIT_SET(field, bit) ? \
211 ((field) &= ~(1<<(bit)), TRUE) : FALSE)
214 ((d == UP) ? "up" : \
215 (d == DOWN) ? "down" : \
216 (d == LEFT) ? "left" : \
217 (d == RIGHT) ? "right" : "oops")
219 #define CLUE2CHAR(c) \
220 ((c < 0) ? ' ' : c + '0')
222 /* Lines that have particular relationships with given dots or squares */
223 #define ABOVE_SQUARE(state, i, j) ((state)->hl[(i) + (state)->w * (j)])
224 #define BELOW_SQUARE(state, i, j) ABOVE_SQUARE(state, i, (j)+1)
225 #define LEFTOF_SQUARE(state, i, j) ((state)->vl[(i) + ((state)->w + 1) * (j)])
226 #define RIGHTOF_SQUARE(state, i, j) LEFTOF_SQUARE(state, (i)+1, j)
229 * These macros return rvalues only, but can cope with being passed
230 * out-of-range coordinates.
232 /* XXX replace these with functions so we can create an array of function
233 * pointers for nicer iteration over them. This could probably be done with
234 * loads of other things for eliminating many nasty hacks. */
235 #define ABOVE_DOT(state, i, j) ((!LEGAL_DOT(state, i, j) || j <= 0) ? \
236 LINE_NO : LV_ABOVE_DOT(state, i, j))
237 #define BELOW_DOT(state, i, j) ((!LEGAL_DOT(state, i, j) || j >= (state)->h) ? \
238 LINE_NO : LV_BELOW_DOT(state, i, j))
240 #define LEFTOF_DOT(state, i, j) ((!LEGAL_DOT(state, i, j) || i <= 0) ? \
241 LINE_NO : LV_LEFTOF_DOT(state, i, j))
242 #define RIGHTOF_DOT(state, i, j) ((!LEGAL_DOT(state, i, j) || i >= (state)->w)? \
243 LINE_NO : LV_RIGHTOF_DOT(state, i, j))
246 * These macros expect to be passed valid coordinates, and return
249 #define LV_BELOW_DOT(state, i, j) ((state)->vl[VL_INDEX(state, i, j)])
250 #define LV_ABOVE_DOT(state, i, j) LV_BELOW_DOT(state, i, (j)-1)
252 #define LV_RIGHTOF_DOT(state, i, j) ((state)->hl[HL_INDEX(state, i, j)])
253 #define LV_LEFTOF_DOT(state, i, j) LV_RIGHTOF_DOT(state, (i)-1, j)
255 /* Counts of interesting things */
256 #define DOT_YES_COUNT(sstate, i, j) \
257 ((sstate)->dot_yescount[DOT_INDEX((sstate)->state, i, j)])
259 #define DOT_NO_COUNT(sstate, i, j) \
260 ((sstate)->dot_nocount[DOT_INDEX((sstate)->state, i, j)])
262 #define SQUARE_YES_COUNT(sstate, i, j) \
263 ((sstate)->square_yescount[SQUARE_INDEX((sstate)->state, i, j)])
265 #define SQUARE_NO_COUNT(sstate, i, j) \
266 ((sstate)->square_nocount[SQUARE_INDEX((sstate)->state, i, j)])
268 /* Iterators. NB these iterate over height more slowly than over width so that
269 * the elements come out in 'reading' order */
270 /* XXX considering adding a 'current' element to each of these which gets the
271 * address of the current dot, say. But expecting we'd need more than that
272 * most of the time. */
273 #define FORALL(i, j, w, h) \
274 for ((j) = 0; (j) < (h); ++(j)) \
275 for ((i) = 0; (i) < (w); ++(i))
277 #define FORALL_DOTS(state, i, j) \
278 FORALL(i, j, (state)->w + 1, (state)->h + 1)
280 #define FORALL_SQUARES(state, i, j) \
281 FORALL(i, j, (state)->w, (state)->h)
283 #define FORALL_HL(state, i, j) \
284 FORALL(i, j, (state)->w, (state)->h+1)
286 #define FORALL_VL(state, i, j) \
287 FORALL(i, j, (state)->w+1, (state)->h)
289 /* ----------------------------------------------------------------------
290 * General struct manipulation and other straightforward code
293 static game_state *dup_game(game_state *state)
295 game_state *ret = snew(game_state);
299 ret->solved = state->solved;
300 ret->cheated = state->cheated;
302 ret->clues = snewn(SQUARE_COUNT(state), char);
303 memcpy(ret->clues, state->clues, SQUARE_COUNT(state));
305 ret->hl = snewn(HL_COUNT(state), char);
306 memcpy(ret->hl, state->hl, HL_COUNT(state));
308 ret->vl = snewn(VL_COUNT(state), char);
309 memcpy(ret->vl, state->vl, VL_COUNT(state));
311 ret->recursion_depth = state->recursion_depth;
316 static void free_game(game_state *state)
326 static solver_state *new_solver_state(const game_state *state, int diff) {
328 solver_state *ret = snew(solver_state);
330 ret->state = dup_game((game_state *)state);
332 ret->recursion_remaining = state->recursion_depth;
333 ret->solver_status = SOLVER_INCOMPLETE;
335 ret->dotdsf = snew_dsf(DOT_COUNT(state));
336 ret->looplen = snewn(DOT_COUNT(state), int);
338 for (i = 0; i < DOT_COUNT(state); i++) {
342 ret->dot_solved = snewn(DOT_COUNT(state), char);
343 ret->square_solved = snewn(SQUARE_COUNT(state), char);
344 memset(ret->dot_solved, FALSE, DOT_COUNT(state));
345 memset(ret->square_solved, FALSE, SQUARE_COUNT(state));
347 ret->dot_yescount = snewn(DOT_COUNT(state), char);
348 memset(ret->dot_yescount, 0, DOT_COUNT(state));
349 ret->dot_nocount = snewn(DOT_COUNT(state), char);
350 memset(ret->dot_nocount, 0, DOT_COUNT(state));
351 ret->square_yescount = snewn(SQUARE_COUNT(state), char);
352 memset(ret->square_yescount, 0, SQUARE_COUNT(state));
353 ret->square_nocount = snewn(SQUARE_COUNT(state), char);
354 memset(ret->square_nocount, 0, SQUARE_COUNT(state));
356 /* dot_nocount needs special initialisation as we define lines coming off
357 * dots on edges as fixed at NO */
359 FORALL_DOTS(state, i, j) {
360 if (i == 0 || i == state->w)
361 ++ret->dot_nocount[DOT_INDEX(state, i, j)];
362 if (j == 0 || j == state->h)
363 ++ret->dot_nocount[DOT_INDEX(state, i, j)];
366 if (diff < DIFF_NORMAL) {
369 ret->normal = snew(normal_mode_state);
371 ret->normal->dot_atmostone = snewn(DOT_COUNT(state), char);
372 memset(ret->normal->dot_atmostone, 0, DOT_COUNT(state));
373 ret->normal->dot_atleastone = snewn(DOT_COUNT(state), char);
374 memset(ret->normal->dot_atleastone, 0, DOT_COUNT(state));
377 if (diff < DIFF_HARD) {
380 ret->hard = snew(hard_mode_state);
381 ret->hard->linedsf = snew_dsf(LINE_COUNT(state));
387 static void free_solver_state(solver_state *sstate) {
389 free_game(sstate->state);
390 sfree(sstate->dotdsf);
391 sfree(sstate->looplen);
392 sfree(sstate->dot_solved);
393 sfree(sstate->square_solved);
394 sfree(sstate->dot_yescount);
395 sfree(sstate->dot_nocount);
396 sfree(sstate->square_yescount);
397 sfree(sstate->square_nocount);
399 if (sstate->normal) {
400 sfree(sstate->normal->dot_atleastone);
401 sfree(sstate->normal->dot_atmostone);
402 sfree(sstate->normal);
406 sfree(sstate->hard->linedsf);
414 static solver_state *dup_solver_state(const solver_state *sstate) {
417 solver_state *ret = snew(solver_state);
419 ret->state = state = dup_game(sstate->state);
421 ret->recursion_remaining = sstate->recursion_remaining;
422 ret->solver_status = sstate->solver_status;
424 ret->dotdsf = snewn(DOT_COUNT(state), int);
425 ret->looplen = snewn(DOT_COUNT(state), int);
426 memcpy(ret->dotdsf, sstate->dotdsf,
427 DOT_COUNT(state) * sizeof(int));
428 memcpy(ret->looplen, sstate->looplen,
429 DOT_COUNT(state) * sizeof(int));
431 ret->dot_solved = snewn(DOT_COUNT(state), char);
432 ret->square_solved = snewn(SQUARE_COUNT(state), char);
433 memcpy(ret->dot_solved, sstate->dot_solved,
435 memcpy(ret->square_solved, sstate->square_solved,
436 SQUARE_COUNT(state));
438 ret->dot_yescount = snewn(DOT_COUNT(state), char);
439 memcpy(ret->dot_yescount, sstate->dot_yescount,
441 ret->dot_nocount = snewn(DOT_COUNT(state), char);
442 memcpy(ret->dot_nocount, sstate->dot_nocount,
445 ret->square_yescount = snewn(SQUARE_COUNT(state), char);
446 memcpy(ret->square_yescount, sstate->square_yescount,
447 SQUARE_COUNT(state));
448 ret->square_nocount = snewn(SQUARE_COUNT(state), char);
449 memcpy(ret->square_nocount, sstate->square_nocount,
450 SQUARE_COUNT(state));
452 if (sstate->normal) {
453 ret->normal = snew(normal_mode_state);
454 ret->normal->dot_atmostone = snewn(DOT_COUNT(state), char);
455 memcpy(ret->normal->dot_atmostone, sstate->normal->dot_atmostone,
458 ret->normal->dot_atleastone = snewn(DOT_COUNT(state), char);
459 memcpy(ret->normal->dot_atleastone, sstate->normal->dot_atleastone,
466 ret->hard = snew(hard_mode_state);
467 ret->hard->linedsf = snewn(LINE_COUNT(state), int);
468 memcpy(ret->hard->linedsf, sstate->hard->linedsf,
469 LINE_COUNT(state) * sizeof(int));
477 static game_params *default_params(void)
479 game_params *ret = snew(game_params);
488 ret->diff = DIFF_EASY;
494 static game_params *dup_params(game_params *params)
496 game_params *ret = snew(game_params);
497 *ret = *params; /* structure copy */
501 static const game_params presets[] = {
502 { 4, 4, DIFF_EASY, 0 },
503 { 4, 4, DIFF_NORMAL, 0 },
504 { 4, 4, DIFF_HARD, 0 },
505 { 7, 7, DIFF_EASY, 0 },
506 { 7, 7, DIFF_NORMAL, 0 },
507 { 7, 7, DIFF_HARD, 0 },
508 { 10, 10, DIFF_EASY, 0 },
509 { 10, 10, DIFF_NORMAL, 0 },
510 { 10, 10, DIFF_HARD, 0 },
512 { 15, 15, DIFF_EASY, 0 },
513 { 15, 15, DIFF_NORMAL, 0 },
514 { 15, 15, DIFF_HARD, 0 },
515 { 30, 20, DIFF_EASY, 0 },
516 { 30, 20, DIFF_NORMAL, 0 },
517 { 30, 20, DIFF_HARD, 0 }
521 static int game_fetch_preset(int i, char **name, game_params **params)
526 if (i < 0 || i >= lenof(presets))
529 tmppar = snew(game_params);
530 *tmppar = presets[i];
532 sprintf(buf, "%dx%d %s", tmppar->h, tmppar->w, diffnames[tmppar->diff]);
538 static void free_params(game_params *params)
543 static void decode_params(game_params *params, char const *string)
545 params->h = params->w = atoi(string);
547 params->diff = DIFF_EASY;
548 while (*string && isdigit((unsigned char)*string)) string++;
549 if (*string == 'x') {
551 params->h = atoi(string);
552 while (*string && isdigit((unsigned char)*string)) string++;
554 if (*string == 'r') {
556 params->rec = atoi(string);
557 while (*string && isdigit((unsigned char)*string)) string++;
559 if (*string == 'd') {
562 for (i = 0; i < DIFF_MAX; i++)
563 if (*string == diffchars[i])
565 if (*string) string++;
569 static char *encode_params(game_params *params, int full)
572 sprintf(str, "%dx%d", params->w, params->h);
574 sprintf(str + strlen(str), "r%dd%c", params->rec, diffchars[params->diff]);
578 static config_item *game_configure(game_params *params)
583 ret = snewn(4, config_item);
585 ret[0].name = "Width";
586 ret[0].type = C_STRING;
587 sprintf(buf, "%d", params->w);
588 ret[0].sval = dupstr(buf);
591 ret[1].name = "Height";
592 ret[1].type = C_STRING;
593 sprintf(buf, "%d", params->h);
594 ret[1].sval = dupstr(buf);
597 ret[2].name = "Difficulty";
598 ret[2].type = C_CHOICES;
599 ret[2].sval = DIFFCONFIG;
600 ret[2].ival = params->diff;
610 static game_params *custom_params(config_item *cfg)
612 game_params *ret = snew(game_params);
614 ret->w = atoi(cfg[0].sval);
615 ret->h = atoi(cfg[1].sval);
617 ret->diff = cfg[2].ival;
622 static char *validate_params(game_params *params, int full)
624 if (params->w < 4 || params->h < 4)
625 return "Width and height must both be at least 4";
627 return "Recursion depth can't be negative";
630 * This shouldn't be able to happen at all, since decode_params
631 * and custom_params will never generate anything that isn't
634 assert(params->diff < DIFF_MAX);
639 /* Returns a newly allocated string describing the current puzzle */
640 static char *state_to_text(const game_state *state)
643 char *description = snewn(SQUARE_COUNT(state) + 1, char);
644 char *dp = description;
648 FORALL_SQUARES(state, i, j) {
649 if (CLUE_AT(state, i, j) < 0) {
650 if (empty_count > 25) {
651 dp += sprintf(dp, "%c", (int)(empty_count + 'a' - 1));
657 dp += sprintf(dp, "%c", (int)(empty_count + 'a' - 1));
660 dp += sprintf(dp, "%c", (int)CLUE2CHAR(CLUE_AT(state, i, j)));
665 dp += sprintf(dp, "%c", (int)(empty_count + 'a' - 1));
667 retval = dupstr(description);
673 /* We require that the params pass the test in validate_params and that the
674 * description fills the entire game area */
675 static char *validate_desc(game_params *params, char *desc)
679 for (; *desc; ++desc) {
680 if (*desc >= '0' && *desc <= '9') {
685 count += *desc - 'a' + 1;
688 return "Unknown character in description";
691 if (count < SQUARE_COUNT(params))
692 return "Description too short for board size";
693 if (count > SQUARE_COUNT(params))
694 return "Description too long for board size";
699 /* Sums the lengths of the numbers in range [0,n) */
700 /* See equivalent function in solo.c for justification of this. */
701 static int len_0_to_n(int n)
703 int len = 1; /* Counting 0 as a bit of a special case */
706 for (i = 1; i < n; i *= 10) {
707 len += max(n - i, 0);
713 static char *encode_solve_move(const game_state *state)
717 /* This is going to return a string representing the moves needed to set
718 * every line in a grid to be the same as the ones in 'state'. The exact
719 * length of this string is predictable. */
721 len = 1; /* Count the 'S' prefix */
722 /* Numbers in horizontal lines */
723 /* Horizontal lines, x position */
724 len += len_0_to_n(state->w) * (state->h + 1);
725 /* Horizontal lines, y position */
726 len += len_0_to_n(state->h + 1) * (state->w);
727 /* Vertical lines, y position */
728 len += len_0_to_n(state->h) * (state->w + 1);
729 /* Vertical lines, x position */
730 len += len_0_to_n(state->w + 1) * (state->h);
731 /* For each line we also have two letters and a comma */
732 len += 3 * (LINE_COUNT(state));
734 ret = snewn(len + 1, char);
737 p += sprintf(p, "S");
739 FORALL_HL(state, i, j) {
740 switch (RIGHTOF_DOT(state, i, j)) {
742 p += sprintf(p, "%d,%dhy", i, j);
745 p += sprintf(p, "%d,%dhn", i, j);
750 FORALL_VL(state, i, j) {
751 switch (BELOW_DOT(state, i, j)) {
753 p += sprintf(p, "%d,%dvy", i, j);
756 p += sprintf(p, "%d,%dvn", i, j);
761 /* No point in doing sums like that if they're going to be wrong */
762 assert(strlen(ret) <= (size_t)len);
766 static game_ui *new_ui(game_state *state)
771 static void free_ui(game_ui *ui)
775 static char *encode_ui(game_ui *ui)
780 static void decode_ui(game_ui *ui, char *encoding)
784 static void game_changed_state(game_ui *ui, game_state *oldstate,
785 game_state *newstate)
789 #define SIZE(d) ((d) * TILE_SIZE + 2 * BORDER + 1)
791 static void game_compute_size(game_params *params, int tilesize,
794 struct { int tilesize; } ads, *ds = &ads;
795 ads.tilesize = tilesize;
797 *x = SIZE(params->w);
798 *y = SIZE(params->h);
801 static void game_set_size(drawing *dr, game_drawstate *ds,
802 game_params *params, int tilesize)
804 ds->tilesize = tilesize;
805 ds->linewidth = max(1,tilesize/16);
808 static float *game_colours(frontend *fe, int *ncolours)
810 float *ret = snewn(4 * NCOLOURS, float);
812 frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
814 ret[COL_FOREGROUND * 3 + 0] = 0.0F;
815 ret[COL_FOREGROUND * 3 + 1] = 0.0F;
816 ret[COL_FOREGROUND * 3 + 2] = 0.0F;
818 ret[COL_HIGHLIGHT * 3 + 0] = 1.0F;
819 ret[COL_HIGHLIGHT * 3 + 1] = 1.0F;
820 ret[COL_HIGHLIGHT * 3 + 2] = 1.0F;
822 ret[COL_MISTAKE * 3 + 0] = 1.0F;
823 ret[COL_MISTAKE * 3 + 1] = 0.0F;
824 ret[COL_MISTAKE * 3 + 2] = 0.0F;
826 *ncolours = NCOLOURS;
830 static game_drawstate *game_new_drawstate(drawing *dr, game_state *state)
832 struct game_drawstate *ds = snew(struct game_drawstate);
834 ds->tilesize = ds->linewidth = 0;
836 ds->hl = snewn(HL_COUNT(state), char);
837 ds->vl = snewn(VL_COUNT(state), char);
838 ds->clue_error = snewn(SQUARE_COUNT(state), char);
841 memset(ds->hl, LINE_UNKNOWN, HL_COUNT(state));
842 memset(ds->vl, LINE_UNKNOWN, VL_COUNT(state));
843 memset(ds->clue_error, 0, SQUARE_COUNT(state));
848 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
850 sfree(ds->clue_error);
856 static int game_timing_state(game_state *state, game_ui *ui)
861 static float game_anim_length(game_state *oldstate, game_state *newstate,
862 int dir, game_ui *ui)
867 static char *game_text_format(game_state *state)
873 len = (2 * state->w + 2) * (2 * state->h + 1);
874 rp = ret = snewn(len + 1, char);
877 switch (ABOVE_SQUARE(state, i, j)) { \
879 rp += sprintf(rp, " -"); \
882 rp += sprintf(rp, " x"); \
885 rp += sprintf(rp, " "); \
888 assert(!"Illegal line state for HL"); \
892 switch (LEFTOF_SQUARE(state, i, j)) { \
894 rp += sprintf(rp, "|"); \
897 rp += sprintf(rp, "x"); \
900 rp += sprintf(rp, " "); \
903 assert(!"Illegal line state for VL"); \
906 for (j = 0; j < state->h; ++j) {
907 for (i = 0; i < state->w; ++i) {
910 rp += sprintf(rp, " \n");
911 for (i = 0; i < state->w; ++i) {
913 rp += sprintf(rp, "%c", (int)CLUE2CHAR(CLUE_AT(state, i, j)));
916 rp += sprintf(rp, "\n");
918 for (i = 0; i < state->w; ++i) {
921 rp += sprintf(rp, " \n");
923 assert(strlen(ret) == len);
927 /* ----------------------------------------------------------------------
932 static void check_caches(const solver_state* sstate)
935 const game_state *state = sstate->state;
937 FORALL_DOTS(state, i, j) {
939 fprintf(stderr, "dot [%d,%d] y: %d %d n: %d %d\n", i, j,
940 dot_order(state, i, j, LINE_YES),
941 sstate->dot_yescount[i + (state->w + 1) * j],
942 dot_order(state, i, j, LINE_NO),
943 sstate->dot_nocount[i + (state->w + 1) * j]);
946 assert(dot_order(state, i, j, LINE_YES) ==
947 DOT_YES_COUNT(sstate, i, j));
948 assert(dot_order(state, i, j, LINE_NO) ==
949 DOT_NO_COUNT(sstate, i, j));
952 FORALL_SQUARES(state, i, j) {
954 fprintf(stderr, "square [%d,%d] y: %d %d n: %d %d\n", i, j,
955 square_order(state, i, j, LINE_YES),
956 sstate->square_yescount[i + state->w * j],
957 square_order(state, i, j, LINE_NO),
958 sstate->square_nocount[i + state->w * j]);
961 assert(square_order(state, i, j, LINE_YES) ==
962 SQUARE_YES_COUNT(sstate, i, j));
963 assert(square_order(state, i, j, LINE_NO) ==
964 SQUARE_NO_COUNT(sstate, i, j));
969 #define check_caches(s) \
971 fprintf(stderr, "check_caches at line %d\n", __LINE__); \
975 #endif /* DEBUG_CACHES */
977 /* ----------------------------------------------------------------------
978 * Solver utility functions
981 static int set_line_bydot(solver_state *sstate, int x, int y, enum direction d,
982 enum line_state line_new
988 game_state *state = sstate->state;
990 /* This line borders at most two squares in our board. We figure out the
991 * x and y positions of those squares so we can record that their yes or no
992 * counts have been changed */
993 int sq1_x=-1, sq1_y=-1, sq2_x=-1, sq2_y=-1;
994 int otherdot_x=-1, otherdot_y=-1;
996 int progress = FALSE;
999 fprintf(stderr, "set_line_bydot [%d,%d], %s, %d\n",
1000 x, y, DIR2STR(d), line_new);
1003 assert(line_new != LINE_UNKNOWN);
1005 check_caches(sstate);
1011 if (LEFTOF_DOT(state, x, y) != line_new) {
1012 LV_LEFTOF_DOT(state, x, y) = line_new;
1026 assert(x < state->w);
1027 if (RIGHTOF_DOT(state, x, y) != line_new) {
1028 LV_RIGHTOF_DOT(state, x, y) = line_new;
1043 if (ABOVE_DOT(state, x, y) != line_new) {
1044 LV_ABOVE_DOT(state, x, y) = line_new;
1058 assert(y < state->h);
1059 if (BELOW_DOT(state, x, y) != line_new) {
1060 LV_BELOW_DOT(state, x, y) = line_new;
1079 fprintf(stderr, "set line [%d,%d] -> [%d,%d] to %s (%s)\n",
1080 x, y, otherdot_x, otherdot_y, line_new == LINE_YES ? "YES" : "NO",
1084 /* Above we updated the cache for the dot that the line in question reaches
1085 * from the dot we've been told about. Here we update that for the dot
1086 * named in our arguments. */
1087 if (line_new == LINE_YES) {
1088 if (sq1_x >= 0 && sq1_y >= 0)
1089 ++SQUARE_YES_COUNT(sstate, sq1_x, sq1_y);
1090 if (sq2_x < state->w && sq2_y < state->h)
1091 ++SQUARE_YES_COUNT(sstate, sq2_x, sq2_y);
1092 ++DOT_YES_COUNT(sstate, x, y);
1093 ++DOT_YES_COUNT(sstate, otherdot_x, otherdot_y);
1095 if (sq1_x >= 0 && sq1_y >= 0)
1096 ++SQUARE_NO_COUNT(sstate, sq1_x, sq1_y);
1097 if (sq2_x < state->w && sq2_y < state->h)
1098 ++SQUARE_NO_COUNT(sstate, sq2_x, sq2_y);
1099 ++DOT_NO_COUNT(sstate, x, y);
1100 ++DOT_NO_COUNT(sstate, otherdot_x, otherdot_y);
1103 check_caches(sstate);
1108 #define set_line_bydot(a, b, c, d, e) \
1109 set_line_bydot(a, b, c, d, e, __FUNCTION__)
1113 * Merge two dots due to the existence of an edge between them.
1114 * Updates the dsf tracking equivalence classes, and keeps track of
1115 * the length of path each dot is currently a part of.
1116 * Returns TRUE if the dots were already linked, ie if they are part of a
1117 * closed loop, and false otherwise.
1119 static int merge_dots(solver_state *sstate, int x1, int y1, int x2, int y2)
1123 i = y1 * (sstate->state->w + 1) + x1;
1124 j = y2 * (sstate->state->w + 1) + x2;
1126 i = dsf_canonify(sstate->dotdsf, i);
1127 j = dsf_canonify(sstate->dotdsf, j);
1132 len = sstate->looplen[i] + sstate->looplen[j];
1133 dsf_merge(sstate->dotdsf, i, j);
1134 i = dsf_canonify(sstate->dotdsf, i);
1135 sstate->looplen[i] = len;
1140 /* Seriously, these should be functions */
1142 #define LINEDSF_INDEX(state, x, y, d) \
1143 ((d == UP) ? ((y-1) * (state->w + 1) + x) : \
1144 (d == DOWN) ? ((y) * (state->w + 1) + x) : \
1145 (d == LEFT) ? ((y) * (state->w) + x-1 + VL_COUNT(state)) : \
1146 (d == RIGHT) ? ((y) * (state->w) + x + VL_COUNT(state)) : \
1147 (assert(!"bad direction value"), 0))
1149 static void linedsf_deindex(const game_state *state, int i,
1150 int *px, int *py, enum direction *pd)
1153 if (i < VL_COUNT(state)) {
1155 *(px) = (i) % (state->w+1);
1156 *(py) = (i) / (state->w+1);
1158 i_mod = i - VL_COUNT(state);
1160 *(px) = (i_mod) % (state->w);
1161 *(py) = (i_mod) / (state->w);
1165 /* Merge two lines because the solver has deduced that they must be either
1166 * identical or opposite. Returns TRUE if this is new information, otherwise
1168 static int merge_lines(solver_state *sstate,
1169 int x1, int y1, enum direction d1,
1170 int x2, int y2, enum direction d2,
1173 , const char *reason
1179 i = LINEDSF_INDEX(sstate->state, x1, y1, d1);
1180 j = LINEDSF_INDEX(sstate->state, x2, y2, d2);
1182 assert(i < LINE_COUNT(sstate->state));
1183 assert(j < LINE_COUNT(sstate->state));
1185 i = edsf_canonify(sstate->hard->linedsf, i, &inv_tmp);
1187 j = edsf_canonify(sstate->hard->linedsf, j, &inv_tmp);
1190 edsf_merge(sstate->hard->linedsf, i, j, inverse);
1194 fprintf(stderr, "%s [%d,%d,%s] [%d,%d,%s] %s(%s)\n",
1196 x1, y1, DIR2STR(d1),
1197 x2, y2, DIR2STR(d2),
1198 inverse ? "inverse " : "", reason);
1205 #define merge_lines(a, b, c, d, e, f, g, h) \
1206 merge_lines(a, b, c, d, e, f, g, h, __FUNCTION__)
1209 /* Return 0 if the given lines are not in the same equivalence class, 1 if they
1210 * are known identical, or 2 if they are known opposite */
1212 static int lines_related(solver_state *sstate,
1213 int x1, int y1, enum direction d1,
1214 int x2, int y2, enum direction d2)
1216 int i, j, inv1, inv2;
1218 i = LINEDSF_INDEX(sstate->state, x1, y1, d1);
1219 j = LINEDSF_INDEX(sstate->state, x2, y2, d2);
1221 i = edsf_canonify(sstate->hard->linedsf, i, &inv1);
1222 j = edsf_canonify(sstate->hard->linedsf, j, &inv2);
1225 return (inv1 == inv2) ? 1 : 2;
1231 /* Count the number of lines of a particular type currently going into the
1232 * given dot. Lines going off the edge of the board are assumed fixed no. */
1233 static int dot_order(const game_state* state, int i, int j, char line_type)
1238 if (line_type == LV_LEFTOF_DOT(state, i, j))
1241 if (line_type == LINE_NO)
1245 if (line_type == LV_RIGHTOF_DOT(state, i, j))
1248 if (line_type == LINE_NO)
1252 if (line_type == LV_ABOVE_DOT(state, i, j))
1255 if (line_type == LINE_NO)
1259 if (line_type == LV_BELOW_DOT(state, i, j))
1262 if (line_type == LINE_NO)
1269 /* Count the number of lines of a particular type currently surrounding the
1271 static int square_order(const game_state* state, int i, int j, char line_type)
1275 if (ABOVE_SQUARE(state, i, j) == line_type)
1277 if (BELOW_SQUARE(state, i, j) == line_type)
1279 if (LEFTOF_SQUARE(state, i, j) == line_type)
1281 if (RIGHTOF_SQUARE(state, i, j) == line_type)
1287 /* Set all lines bordering a dot of type old_type to type new_type
1288 * Return value tells caller whether this function actually did anything */
1289 static int dot_setall(solver_state *sstate, int i, int j,
1290 char old_type, char new_type)
1292 int retval = FALSE, r;
1293 game_state *state = sstate->state;
1295 if (old_type == new_type)
1298 if (i > 0 && LEFTOF_DOT(state, i, j) == old_type) {
1299 r = set_line_bydot(sstate, i, j, LEFT, new_type);
1304 if (i < state->w && RIGHTOF_DOT(state, i, j) == old_type) {
1305 r = set_line_bydot(sstate, i, j, RIGHT, new_type);
1310 if (j > 0 && ABOVE_DOT(state, i, j) == old_type) {
1311 r = set_line_bydot(sstate, i, j, UP, new_type);
1316 if (j < state->h && BELOW_DOT(state, i, j) == old_type) {
1317 r = set_line_bydot(sstate, i, j, DOWN, new_type);
1325 /* Set all lines bordering a square of type old_type to type new_type */
1326 static int square_setall(solver_state *sstate, int i, int j,
1327 char old_type, char new_type)
1330 game_state *state = sstate->state;
1333 fprintf(stderr, "square_setall [%d,%d] from %d to %d\n", i, j,
1334 old_type, new_type);
1336 if (ABOVE_SQUARE(state, i, j) == old_type) {
1337 r = set_line_bydot(sstate, i, j, RIGHT, new_type);
1340 if (BELOW_SQUARE(state, i, j) == old_type) {
1341 r = set_line_bydot(sstate, i, j+1, RIGHT, new_type);
1344 if (LEFTOF_SQUARE(state, i, j) == old_type) {
1345 r = set_line_bydot(sstate, i, j, DOWN, new_type);
1348 if (RIGHTOF_SQUARE(state, i, j) == old_type) {
1349 r = set_line_bydot(sstate, i+1, j, DOWN, new_type);
1356 /* ----------------------------------------------------------------------
1357 * Loop generation and clue removal
1360 /* We're going to store a list of current candidate squares for lighting.
1361 * Each square gets a 'score', which tells us how adding that square right
1362 * now would affect the length of the solution loop. We're trying to
1363 * maximise that quantity so will bias our random selection of squares to
1364 * light towards those with high scores */
1367 unsigned long random;
1371 static int get_square_cmpfn(void *v1, void *v2)
1373 struct square *s1 = v1;
1374 struct square *s2 = v2;
1388 static int square_sort_cmpfn(void *v1, void *v2)
1390 struct square *s1 = v1;
1391 struct square *s2 = v2;
1394 r = s2->score - s1->score;
1399 if (s1->random < s2->random)
1401 else if (s1->random > s2->random)
1405 * It's _just_ possible that two squares might have been given
1406 * the same random value. In that situation, fall back to
1407 * comparing based on the coordinates. This introduces a tiny
1408 * directional bias, but not a significant one.
1410 return get_square_cmpfn(v1, v2);
1413 enum { SQUARE_LIT, SQUARE_UNLIT };
1415 #define SQUARE_STATE(i, j) \
1416 ( LEGAL_SQUARE(state, i, j) ? \
1417 LV_SQUARE_STATE(i,j) : \
1420 #define LV_SQUARE_STATE(i, j) board[SQUARE_INDEX(state, i, j)]
1422 /* Generate a new complete set of clues for the given game_state (respecting
1423 * the dimensions provided by said game_state) */
1424 static void add_full_clues(game_state *state, random_state *rs)
1429 int board_area = SQUARE_COUNT(state);
1432 struct square *square, *tmpsquare, *sq;
1433 struct square square_pos;
1435 /* These will contain exactly the same information, sorted into different
1437 tree234 *lightable_squares_sorted, *lightable_squares_gettable;
1439 #define SQUARE_REACHABLE(i,j) \
1440 (t = (SQUARE_STATE(i-1, j) == SQUARE_LIT || \
1441 SQUARE_STATE(i+1, j) == SQUARE_LIT || \
1442 SQUARE_STATE(i, j-1) == SQUARE_LIT || \
1443 SQUARE_STATE(i, j+1) == SQUARE_LIT), \
1446 /* One situation in which we may not light a square is if that'll leave one
1447 * square above/below and one left/right of us unlit, separated by a lit
1448 * square diagnonal from us */
1449 #define SQUARE_DIAGONAL_VIOLATION(i, j, h, v) \
1450 (t = (SQUARE_STATE((i)+(h), (j)) == SQUARE_UNLIT && \
1451 SQUARE_STATE((i), (j)+(v)) == SQUARE_UNLIT && \
1452 SQUARE_STATE((i)+(h), (j)+(v)) == SQUARE_LIT), \
1455 /* We also may not light a square if it will form a loop of lit squares
1456 * around some unlit squares, as then the game soln won't have a single
1458 #define SQUARE_LOOP_VIOLATION(i, j, lit1, lit2) \
1459 (SQUARE_STATE((i)+1, (j)) == lit1 && \
1460 SQUARE_STATE((i)-1, (j)) == lit1 && \
1461 SQUARE_STATE((i), (j)+1) == lit2 && \
1462 SQUARE_STATE((i), (j)-1) == lit2)
1464 #define CAN_LIGHT_SQUARE(i, j) \
1465 (SQUARE_REACHABLE(i, j) && \
1466 !SQUARE_DIAGONAL_VIOLATION(i, j, -1, -1) && \
1467 !SQUARE_DIAGONAL_VIOLATION(i, j, +1, -1) && \
1468 !SQUARE_DIAGONAL_VIOLATION(i, j, -1, +1) && \
1469 !SQUARE_DIAGONAL_VIOLATION(i, j, +1, +1) && \
1470 !SQUARE_LOOP_VIOLATION(i, j, SQUARE_LIT, SQUARE_UNLIT) && \
1471 !SQUARE_LOOP_VIOLATION(i, j, SQUARE_UNLIT, SQUARE_LIT))
1473 #define IS_LIGHTING_CANDIDATE(i, j) \
1474 (SQUARE_STATE(i, j) == SQUARE_UNLIT && \
1475 CAN_LIGHT_SQUARE(i,j))
1477 /* The 'score' of a square reflects its current desirability for selection
1478 * as the next square to light. We want to encourage moving into uncharted
1479 * areas so we give scores according to how many of the square's neighbours
1480 * are currently unlit. */
1487 #define SQUARE_SCORE(i,j) \
1488 (2*((SQUARE_STATE(i-1, j) == SQUARE_UNLIT) + \
1489 (SQUARE_STATE(i+1, j) == SQUARE_UNLIT) + \
1490 (SQUARE_STATE(i, j-1) == SQUARE_UNLIT) + \
1491 (SQUARE_STATE(i, j+1) == SQUARE_UNLIT)) - 4)
1493 /* When a square gets lit, this defines how far away from that square we
1494 * need to go recomputing scores */
1495 #define SCORE_DISTANCE 1
1497 board = snewn(board_area, char);
1498 clues = state->clues;
1501 memset(board, SQUARE_UNLIT, board_area);
1503 /* Seed the board with a single lit square near the middle */
1506 if (state->w & 1 && random_bits(rs, 1))
1508 if (state->h & 1 && random_bits(rs, 1))
1511 LV_SQUARE_STATE(i, j) = SQUARE_LIT;
1513 /* We need a way of favouring squares that will increase our loopiness.
1514 * We do this by maintaining a list of all candidate squares sorted by
1515 * their score and choose randomly from that with appropriate skew.
1516 * In order to avoid consistently biasing towards particular squares, we
1517 * need the sort order _within_ each group of scores to be completely
1518 * random. But it would be abusing the hospitality of the tree234 data
1519 * structure if our comparison function were nondeterministic :-). So with
1520 * each square we associate a random number that does not change during a
1521 * particular run of the generator, and use that as a secondary sort key.
1522 * Yes, this means we will be biased towards particular random squares in
1523 * any one run but that doesn't actually matter. */
1525 lightable_squares_sorted = newtree234(square_sort_cmpfn);
1526 lightable_squares_gettable = newtree234(get_square_cmpfn);
1527 #define ADD_SQUARE(s) \
1529 sq = add234(lightable_squares_sorted, s); \
1531 sq = add234(lightable_squares_gettable, s); \
1535 #define REMOVE_SQUARE(s) \
1537 sq = del234(lightable_squares_sorted, s); \
1539 sq = del234(lightable_squares_gettable, s); \
1543 #define HANDLE_DIR(a, b) \
1544 square = snew(struct square); \
1545 square->x = (i)+(a); \
1546 square->y = (j)+(b); \
1547 square->score = 2; \
1548 square->random = random_bits(rs, 31); \
1556 /* Light squares one at a time until the board is interesting enough */
1559 /* We have count234(lightable_squares) possibilities, and in
1560 * lightable_squares_sorted they are sorted with the most desirable
1562 c = count234(lightable_squares_sorted);
1565 assert(c == count234(lightable_squares_gettable));
1567 /* Check that the best square available is any good */
1568 square = (struct square *)index234(lightable_squares_sorted, 0);
1572 * We never want to _decrease_ the loop's perimeter. Making
1573 * moves that leave the perimeter the same is occasionally
1574 * useful: if it were _never_ done then the user would be
1575 * able to deduce illicitly that any degree-zero vertex was
1576 * on the outside of the loop. So we do it sometimes but
1579 if (square->score < 0 || (square->score == 0 &&
1580 random_upto(rs, 2) == 0)) {
1584 assert(square->score == SQUARE_SCORE(square->x, square->y));
1585 assert(SQUARE_STATE(square->x, square->y) == SQUARE_UNLIT);
1586 assert(square->x >= 0 && square->x < state->w);
1587 assert(square->y >= 0 && square->y < state->h);
1589 /* Update data structures */
1590 LV_SQUARE_STATE(square->x, square->y) = SQUARE_LIT;
1591 REMOVE_SQUARE(square);
1593 /* We might have changed the score of any squares up to 2 units away in
1595 for (b = -SCORE_DISTANCE; b <= SCORE_DISTANCE; b++) {
1596 for (a = -SCORE_DISTANCE; a <= SCORE_DISTANCE; a++) {
1599 square_pos.x = square->x + a;
1600 square_pos.y = square->y + b;
1601 if (square_pos.x < 0 || square_pos.x >= state->w ||
1602 square_pos.y < 0 || square_pos.y >= state->h) {
1605 tmpsquare = find234(lightable_squares_gettable, &square_pos,
1608 assert(tmpsquare->x == square_pos.x);
1609 assert(tmpsquare->y == square_pos.y);
1610 assert(SQUARE_STATE(tmpsquare->x, tmpsquare->y) ==
1612 REMOVE_SQUARE(tmpsquare);
1614 tmpsquare = snew(struct square);
1615 tmpsquare->x = square_pos.x;
1616 tmpsquare->y = square_pos.y;
1617 tmpsquare->random = random_bits(rs, 31);
1619 tmpsquare->score = SQUARE_SCORE(tmpsquare->x, tmpsquare->y);
1621 if (IS_LIGHTING_CANDIDATE(tmpsquare->x, tmpsquare->y)) {
1622 ADD_SQUARE(tmpsquare);
1632 while ((square = delpos234(lightable_squares_gettable, 0)) != NULL)
1634 freetree234(lightable_squares_gettable);
1635 freetree234(lightable_squares_sorted);
1637 /* Copy out all the clues */
1638 FORALL_SQUARES(state, i, j) {
1639 c = SQUARE_STATE(i, j);
1640 LV_CLUE_AT(state, i, j) = 0;
1641 if (SQUARE_STATE(i-1, j) != c) ++LV_CLUE_AT(state, i, j);
1642 if (SQUARE_STATE(i+1, j) != c) ++LV_CLUE_AT(state, i, j);
1643 if (SQUARE_STATE(i, j-1) != c) ++LV_CLUE_AT(state, i, j);
1644 if (SQUARE_STATE(i, j+1) != c) ++LV_CLUE_AT(state, i, j);
1650 static int game_has_unique_soln(const game_state *state, int diff)
1653 solver_state *sstate_new;
1654 solver_state *sstate = new_solver_state((game_state *)state, diff);
1656 sstate_new = solve_game_rec(sstate, diff);
1658 assert(sstate_new->solver_status != SOLVER_MISTAKE);
1659 ret = (sstate_new->solver_status == SOLVER_SOLVED);
1661 free_solver_state(sstate_new);
1662 free_solver_state(sstate);
1667 /* Remove clues one at a time at random. */
1668 static game_state *remove_clues(game_state *state, random_state *rs,
1671 int *square_list, squares;
1672 game_state *ret = dup_game(state), *saved_ret;
1678 /* We need to remove some clues. We'll do this by forming a list of all
1679 * available clues, shuffling it, then going along one at a
1680 * time clearing each clue in turn for which doing so doesn't render the
1681 * board unsolvable. */
1682 squares = state->w * state->h;
1683 square_list = snewn(squares, int);
1684 for (n = 0; n < squares; ++n) {
1688 shuffle(square_list, squares, sizeof(int), rs);
1690 for (n = 0; n < squares; ++n) {
1691 saved_ret = dup_game(ret);
1692 LV_CLUE_AT(ret, square_list[n] % state->w,
1693 square_list[n] / state->w) = -1;
1696 desc = state_to_text(ret);
1697 fprintf(stderr, "%dx%d:%s\n", state->w, state->h, desc);
1701 if (game_has_unique_soln(ret, diff)) {
1702 free_game(saved_ret);
1713 static char *new_game_desc(game_params *params, random_state *rs,
1714 char **aux, int interactive)
1716 /* solution and description both use run-length encoding in obvious ways */
1718 game_state *state = snew(game_state), *state_new;
1720 state->h = params->h;
1721 state->w = params->w;
1723 state->clues = snewn(SQUARE_COUNT(params), char);
1724 state->hl = snewn(HL_COUNT(params), char);
1725 state->vl = snewn(VL_COUNT(params), char);
1728 memset(state->hl, LINE_UNKNOWN, HL_COUNT(params));
1729 memset(state->vl, LINE_UNKNOWN, VL_COUNT(params));
1731 state->solved = state->cheated = FALSE;
1732 state->recursion_depth = params->rec;
1734 /* Get a new random solvable board with all its clues filled in. Yes, this
1735 * can loop for ever if the params are suitably unfavourable, but
1736 * preventing games smaller than 4x4 seems to stop this happening */
1739 add_full_clues(state, rs);
1740 } while (!game_has_unique_soln(state, params->diff));
1742 state_new = remove_clues(state, rs, params->diff);
1746 if (params->diff > 0 && game_has_unique_soln(state, params->diff-1)) {
1748 fprintf(stderr, "Rejecting board, it is too easy\n");
1750 goto newboard_please;
1753 retval = state_to_text(state);
1757 assert(!validate_desc(params, retval));
1762 static game_state *new_game(midend *me, game_params *params, char *desc)
1765 game_state *state = snew(game_state);
1766 int empties_to_make = 0;
1768 const char *dp = desc;
1770 state->recursion_depth = 0; /* XXX pending removal, probably */
1772 state->h = params->h;
1773 state->w = params->w;
1775 state->clues = snewn(SQUARE_COUNT(params), char);
1776 state->hl = snewn(HL_COUNT(params), char);
1777 state->vl = snewn(VL_COUNT(params), char);
1779 state->solved = state->cheated = FALSE;
1781 FORALL_SQUARES(params, i, j) {
1782 if (empties_to_make) {
1784 LV_CLUE_AT(state, i, j) = -1;
1790 if (n >= 0 && n < 10) {
1791 LV_CLUE_AT(state, i, j) = n;
1795 LV_CLUE_AT(state, i, j) = -1;
1796 empties_to_make = n - 1;
1801 memset(state->hl, LINE_UNKNOWN, HL_COUNT(params));
1802 memset(state->vl, LINE_UNKNOWN, VL_COUNT(params));
1807 enum { LOOP_NONE=0, LOOP_SOLN, LOOP_NOT_SOLN };
1809 /* ----------------------------------------------------------------------
1812 * Our solver modes operate as follows. Each mode also uses the modes above it.
1815 * Just implement the rules of the game.
1818 * For each pair of lines through each dot we store a bit for whether
1819 * at least one of them is on and whether at most one is on. (If we know
1820 * both or neither is on that's already stored more directly.) That's six
1821 * bits per dot. Bit number n represents the lines shown in dline_desc.
1824 * Use edsf data structure to make equivalence classes of lines that are
1825 * known identical to or opposite to one another.
1828 /* The order the following are defined in is very important, see below.
1829 * The last two fields may seem non-obvious: they specify that when talking
1830 * about a square the dx and dy offsets should be added to the square coords to
1831 * get to the right dot. Where dx and dy are -1 this means that the dline
1832 * doesn't make sense for a square. */
1833 /* XXX can this be done with a struct instead? */
1835 DLINE(DLINE_UD, UP, DOWN, -1, -1) \
1836 DLINE(DLINE_LR, LEFT, RIGHT, -1, -1) \
1837 DLINE(DLINE_UR, UP, RIGHT, 0, 1) \
1838 DLINE(DLINE_DL, DOWN, LEFT, 1, 0) \
1839 DLINE(DLINE_UL, UP, LEFT, 1, 1) \
1840 DLINE(DLINE_DR, DOWN, RIGHT, 0, 0)
1842 #define OPP_DLINE(dline_desc) ((dline_desc) ^ 1)
1845 #define DLINE(desc, dir1, dir2, dx, dy) \
1852 enum dline_desc desc;
1853 enum direction dir1, dir2;
1857 const static struct dline dlines[] = {
1858 #define DLINE(desc, dir1, dir2, dx, dy) \
1859 { desc, dir1, dir2, dx, dy },
1864 #define FORALL_DOT_DLINES(dl_iter) \
1865 for (dl_iter = 0; dl_iter < lenof(dlines); ++dl_iter)
1867 #define FORALL_SQUARE_DLINES(dl_iter) \
1868 for (dl_iter = 2; dl_iter < lenof(dlines); ++dl_iter)
1871 ((d==DLINE_UD) ? "DLINE_UD": \
1872 (d==DLINE_LR) ? "DLINE_LR": \
1873 (d==DLINE_UR) ? "DLINE_UR": \
1874 (d==DLINE_DL) ? "DLINE_DL": \
1875 (d==DLINE_UL) ? "DLINE_UL": \
1876 (d==DLINE_DR) ? "DLINE_DR": \
1879 static const struct dline *get_dline(enum dline_desc desc)
1881 return &dlines[desc];
1884 /* This will fail an assertion if the directions handed to it are the same, as
1885 * no dline corresponds to that */
1886 static enum dline_desc dline_desc_from_dirs(enum direction dir1,
1887 enum direction dir2)
1891 assert (dir1 != dir2);
1893 for (i = 0; i < lenof(dlines); ++i) {
1894 if ((dir1 == dlines[i].dir1 && dir2 == dlines[i].dir2) ||
1895 (dir1 == dlines[i].dir2 && dir2 == dlines[i].dir1)) {
1896 return dlines[i].desc;
1900 assert(!"dline not found");
1901 return DLINE_UD; /* placate compiler */
1904 /* The following functions allow you to get or set info about the selected
1905 * dline corresponding to the dot or square at [i,j]. You'll get an assertion
1906 * failure if you talk about a dline that doesn't exist, ie if you ask about
1907 * non-touching lines around a square. */
1908 static int get_dot_dline(const game_state *state, const char *dline_array,
1909 int i, int j, enum dline_desc desc)
1911 /* fprintf(stderr, "get_dot_dline %p [%d,%d] %s\n", dline_array, i, j, DL2STR(desc)); */
1912 return BIT_SET(dline_array[i + (state->w + 1) * j], desc);
1915 static int set_dot_dline(game_state *state, char *dline_array,
1916 int i, int j, enum dline_desc desc
1918 , const char *reason
1923 ret = SET_BIT(dline_array[i + (state->w + 1) * j], desc);
1927 fprintf(stderr, "set_dot_dline %p [%d,%d] %s (%s)\n", dline_array, i, j, DL2STR(desc), reason);
1932 static int get_square_dline(game_state *state, char *dline_array,
1933 int i, int j, enum dline_desc desc)
1935 const struct dline *dl = get_dline(desc);
1936 assert(dl->dx != -1 && dl->dy != -1);
1937 /* fprintf(stderr, "get_square_dline %p [%d,%d] %s\n", dline_array, i, j, DL2STR(desc)); */
1938 return BIT_SET(dline_array[(i+dl->dx) + (state->w + 1) * (j+dl->dy)],
1942 static int set_square_dline(game_state *state, char *dline_array,
1943 int i, int j, enum dline_desc desc
1945 , const char *reason
1949 const struct dline *dl = get_dline(desc);
1951 assert(dl->dx != -1 && dl->dy != -1);
1952 ret = SET_BIT(dline_array[(i+dl->dx) + (state->w + 1) * (j+dl->dy)], desc);
1955 fprintf(stderr, "set_square_dline %p [%d,%d] %s (%s)\n", dline_array, i, j, DL2STR(desc), reason);
1961 #define set_dot_dline(a, b, c, d, e) \
1962 set_dot_dline(a, b, c, d, e, __FUNCTION__)
1963 #define set_square_dline(a, b, c, d, e) \
1964 set_square_dline(a, b, c, d, e, __FUNCTION__)
1967 static int set_dot_opp_dline(game_state *state, char *dline_array,
1968 int i, int j, enum dline_desc desc)
1970 return set_dot_dline(state, dline_array, i, j, OPP_DLINE(desc));
1973 static int set_square_opp_dline(game_state *state, char *dline_array,
1974 int i, int j, enum dline_desc desc)
1976 return set_square_dline(state, dline_array, i, j, OPP_DLINE(desc));
1979 /* Find out if both the lines in the given dline are UNKNOWN */
1980 static int dline_both_unknown(const game_state *state, int i, int j,
1981 enum dline_desc desc)
1983 const struct dline *dl = get_dline(desc);
1985 (get_line_status_from_point(state, i, j, dl->dir1) == LINE_UNKNOWN) &&
1986 (get_line_status_from_point(state, i, j, dl->dir2) == LINE_UNKNOWN);
1989 #define SQUARE_DLINES \
1990 HANDLE_DLINE(DLINE_UL, RIGHTOF_SQUARE, BELOW_SQUARE, 1, 1); \
1991 HANDLE_DLINE(DLINE_UR, LEFTOF_SQUARE, BELOW_SQUARE, 0, 1); \
1992 HANDLE_DLINE(DLINE_DL, RIGHTOF_SQUARE, ABOVE_SQUARE, 1, 0); \
1993 HANDLE_DLINE(DLINE_DR, LEFTOF_SQUARE, ABOVE_SQUARE, 0, 0);
1995 #define DOT_DLINES \
1996 HANDLE_DLINE(DLINE_UD, ABOVE_DOT, BELOW_DOT); \
1997 HANDLE_DLINE(DLINE_LR, LEFTOF_DOT, RIGHTOF_DOT); \
1998 HANDLE_DLINE(DLINE_UL, ABOVE_DOT, LEFTOF_DOT); \
1999 HANDLE_DLINE(DLINE_UR, ABOVE_DOT, RIGHTOF_DOT); \
2000 HANDLE_DLINE(DLINE_DL, BELOW_DOT, LEFTOF_DOT); \
2001 HANDLE_DLINE(DLINE_DR, BELOW_DOT, RIGHTOF_DOT);
2003 static void array_setall(char *array, char from, char to, int len)
2005 char *p = array, *p_old = p;
2006 int len_remaining = len;
2008 while ((p = memchr(p, from, len_remaining))) {
2010 len_remaining -= p - p_old;
2017 static int get_line_status_from_point(const game_state *state,
2018 int x, int y, enum direction d)
2022 return LEFTOF_DOT(state, x, y);
2024 return RIGHTOF_DOT(state, x, y);
2026 return ABOVE_DOT(state, x, y);
2028 return BELOW_DOT(state, x, y);
2034 /* First and second args are coord offset from top left of square to one end
2035 * of line in question, third and fourth args are the direction from the first
2036 * end of the line to the second. Fifth arg is the direction of the line from
2037 * the coord offset position.
2040 #define SQUARE_LINES \
2041 SQUARE_LINE( 0, 0, RIGHT, RIGHTOF_DOT, UP); \
2042 SQUARE_LINE( 0, +1, RIGHT, RIGHTOF_DOT, DOWN); \
2043 SQUARE_LINE( 0, 0, DOWN, BELOW_DOT, LEFT); \
2044 SQUARE_LINE(+1, 0, DOWN, BELOW_DOT, RIGHT);
2046 /* Set pairs of lines around this square which are known to be identical to
2047 * the given line_state */
2048 static int square_setall_identical(solver_state *sstate, int x, int y,
2049 enum line_state line_new)
2051 /* can[dir] contains the canonical line associated with the line in
2052 * direction dir from the square in question. Similarly inv[dir] is
2053 * whether or not the line in question is inverse to its canonical
2055 int can[4], inv[4], i, j;
2061 fprintf(stderr, "Setting all identical unknown lines around square "
2062 "[%d,%d] to %d:\n", x, y, line_new);
2065 #define SQUARE_LINE(dx, dy, linedir, dir_dot, sqdir) \
2067 edsf_canonify(sstate->hard->linedsf, \
2068 LINEDSF_INDEX(sstate->state, x+(dx), y+(dy), linedir), \
2075 for (j = 0; j < 4; ++j) {
2076 for (i = 0; i < 4; ++i) {
2080 if (can[i] == can[j] && inv[i] == inv[j]) {
2082 /* Lines in directions i and j are identical.
2083 * Only do j now, we'll do i when the loop causes us to
2084 * consider {i,j} in the opposite order. */
2085 #define SQUARE_LINE(dx, dy, dir, c, sqdir) \
2087 retval = set_line_bydot(sstate, x+(dx), y+(dy), dir, line_new); \
2104 /* Set all identical lines passing through the current dot to the chosen line
2105 * state. (implicitly this only looks at UNKNOWN lines) */
2106 static int dot_setall_identical(solver_state *sstate, int x, int y,
2107 enum line_state line_new)
2109 /* The implementation of this is a little naughty but I can't see how to do
2110 * it elegantly any other way */
2111 int can[4], inv[4], i, j;
2115 for (d = 0; d < 4; ++d) {
2116 can[d] = edsf_canonify(sstate->hard->linedsf,
2117 LINEDSF_INDEX(sstate->state, x, y, d),
2121 for (j = 0; j < 4; ++j) {
2123 for (i = 0; i < j; ++i) {
2124 if (can[i] == can[j] && inv[i] == inv[j]) {
2125 /* Lines in directions i and j are identical */
2126 if (get_line_status_from_point(sstate->state, x, y, j) ==
2128 set_line_bydot(sstate->state, x, y, j,
2142 static int square_setboth_in_dline(solver_state *sstate, enum dline_desc dd,
2143 int i, int j, enum line_state line_new)
2146 const struct dline *dl = get_dline(dd);
2149 fprintf(stderr, "square_setboth_in_dline %s [%d,%d] to %d\n",
2150 DL2STR(dd), i, j, line_new);
2153 assert(dl->dx != -1 && dl->dy != -1);
2156 set_line_bydot(sstate, i+dl->dx, j+dl->dy, dl->dir1, line_new);
2158 set_line_bydot(sstate, i+dl->dx, j+dl->dy, dl->dir2, line_new);
2163 /* Call this function to register that the two unknown lines going into the dot
2164 * [x,y] are identical or opposite (depending on the value of 'inverse'). This
2165 * function will cause an assertion failure if anything other than exactly two
2166 * lines into the dot are unknown.
2167 * As usual returns TRUE if any progress was made, otherwise FALSE. */
2168 static int dot_relate_2_unknowns(solver_state *sstate, int x, int y, int inverse)
2170 enum direction d1=DOWN, d2=DOWN; /* Just to keep compiler quiet */
2173 #define TRY_DIR(d) \
2174 if (get_line_status_from_point(sstate->state, x, y, d) == \
2176 if (dirs_set == 0) \
2179 assert(dirs_set == 1); \
2191 assert(dirs_set == 2);
2195 fprintf(stderr, "Lines in direction %s and %s from dot [%d,%d] are %s\n",
2196 DIR2STR(d1), DIR2STR(d2), x, y, inverse?"opposite":"the same");
2199 return merge_lines(sstate, x, y, d1, x, y, d2, inverse);
2202 /* Very similar to dot_relate_2_unknowns. */
2203 static int square_relate_2_unknowns(solver_state *sstate, int x, int y, int inverse)
2205 enum direction d1=DOWN, d2=DOWN;
2206 int x1=-1, y1=-1, x2=-1, y2=-1;
2210 fprintf(stderr, "2 unknowns around square [%d,%d] are %s\n",
2211 x, y, inverse?"opposite":"the same");
2214 #define TRY_DIR(i, j, d, dir_sq) \
2216 if (dir_sq(sstate->state, x, y) == LINE_UNKNOWN) { \
2217 if (dirs_set == 0) { \
2218 d1 = d; x1 = i; y1 = j; \
2220 assert(dirs_set == 1); \
2221 d2 = d; x2 = i; y2 = j; \
2227 TRY_DIR(x, y, RIGHT, ABOVE_SQUARE);
2228 TRY_DIR(x, y, DOWN, LEFTOF_SQUARE);
2229 TRY_DIR(x+1, y, DOWN, RIGHTOF_SQUARE);
2230 TRY_DIR(x, y+1, RIGHT, BELOW_SQUARE);
2233 assert(dirs_set == 2);
2236 fprintf(stderr, "Line in direction %s from dot [%d,%d] and line in direction %s from dot [%2d,%2d] are %s\n",
2237 DIR2STR(d1), x1, y1, DIR2STR(d2), x2, y2, inverse?"opposite":"the same");
2240 return merge_lines(sstate, x1, y1, d1, x2, y2, d2, inverse);
2243 /* Figure out if any dlines can be 'collapsed' (and do so if they can). This
2244 * can happen if one of the lines is known and due to the dline status this
2245 * tells us state of the other, or if there's an interaction with the linedsf
2246 * (ie if atmostone is set for a dline and the lines are known identical they
2247 * must both be LINE_NO, etc). XXX at the moment only the former is
2248 * implemented, and indeed the latter should be implemented in the hard mode
2251 static int dot_collapse_dlines(solver_state *sstate, int i, int j)
2253 int progress = FALSE;
2254 enum direction dir1, dir2;
2257 game_state *state = sstate->state;
2260 for (dir1 = 0; dir1 < 4; dir1++) {
2261 dir1st = get_line_status_from_point(state, i, j, dir1);
2262 if (dir1st == LINE_UNKNOWN)
2264 /* dir2 iterates over the whole range rather than starting at dir1+1
2265 * because test below is asymmetric */
2266 for (dir2 = 0; dir2 < 4; dir2++) {
2270 if ((i == 0 && (dir1 == LEFT || dir2 == LEFT)) ||
2271 (j == 0 && (dir1 == UP || dir2 == UP)) ||
2272 (i == state->w && (dir1 == RIGHT || dir2 == RIGHT)) ||
2273 (j == state->h && (dir1 == DOWN || dir2 == DOWN))) {
2278 fprintf(stderr, "dot_collapse_dlines [%d,%d], %s %s\n", i, j,
2279 DIR2STR(dir1), DIR2STR(dir2));
2282 if (get_line_status_from_point(state, i, j, dir2) ==
2284 dd = dline_desc_from_dirs(dir1, dir2);
2286 dlset = get_dot_dline(state, sstate->normal->dot_atmostone, i, j, dd);
2287 if (dlset && dir1st == LINE_YES) {
2288 /* fprintf(stderr, "setting %s to NO\n", DIR2STR(dir2)); */
2290 set_line_bydot(sstate, i, j, dir2, LINE_NO);
2293 dlset = get_dot_dline(state, sstate->normal->dot_atleastone, i, j, dd);
2294 if (dlset && dir1st == LINE_NO) {
2295 /* fprintf(stderr, "setting %s to YES\n", DIR2STR(dir2)); */
2297 set_line_bydot(sstate, i, j, dir2, LINE_YES);
2307 * These are the main solver functions.
2309 * Their return values are diff values corresponding to the lowest mode solver
2310 * that would notice the work that they have done. For example if the normal
2311 * mode solver adds actual lines or crosses, it will return DIFF_EASY as the
2312 * easy mode solver might be able to make progress using that. It doesn't make
2313 * sense for one of them to return a diff value higher than that of the
2316 * Each function returns the lowest value it can, as early as possible, in
2317 * order to try and pass as much work as possible back to the lower level
2318 * solvers which progress more quickly.
2321 /* PROPOSED NEW DESIGN:
2322 * We have a work queue consisting of 'events' notifying us that something has
2323 * happened that a particular solver mode might be interested in. For example
2324 * the hard mode solver might do something that helps the normal mode solver at
2325 * dot [x,y] in which case it will enqueue an event recording this fact. Then
2326 * we pull events off the work queue, and hand each in turn to the solver that
2327 * is interested in them. If a solver reports that it failed we pass the same
2328 * event on to progressively more advanced solvers and the loop detector. Once
2329 * we've exhausted an event, or it has helped us progress, we drop it and
2330 * continue to the next one. The events are sorted first in order of solver
2331 * complexity (easy first) then order of insertion (oldest first).
2332 * Once we run out of events we loop over each permitted solver in turn
2333 * (easiest first) until either a deduction is made (and an event therefore
2334 * emerges) or no further deductions can be made (in which case we've failed).
2337 * * How do we 'loop over' a solver when both dots and squares are concerned.
2338 * Answer: first all squares then all dots.
2341 static int easy_mode_deductions(solver_state *sstate)
2343 int i, j, h, w, current_yes, current_no;
2345 int diff = DIFF_MAX;
2347 state = sstate->state;
2351 /* Per-square deductions */
2352 FORALL_SQUARES(state, i, j) {
2353 if (sstate->square_solved[SQUARE_INDEX(state, i, j)])
2356 current_yes = SQUARE_YES_COUNT(sstate, i, j);
2357 current_no = SQUARE_NO_COUNT(sstate, i, j);
2359 if (current_yes + current_no == 4) {
2360 sstate->square_solved[SQUARE_INDEX(state, i, j)] = TRUE;
2361 /* diff = min(diff, DIFF_EASY); */
2365 if (CLUE_AT(state, i, j) < 0)
2368 if (CLUE_AT(state, i, j) < current_yes) {
2370 fprintf(stderr, "detected error [%d,%d] in %s at line %d\n", i, j, __FUNCTION__, __LINE__);
2372 sstate->solver_status = SOLVER_MISTAKE;
2375 if (CLUE_AT(state, i, j) == current_yes) {
2376 if (square_setall(sstate, i, j, LINE_UNKNOWN, LINE_NO))
2377 diff = min(diff, DIFF_EASY);
2378 sstate->square_solved[SQUARE_INDEX(state, i, j)] = TRUE;
2382 if (4 - CLUE_AT(state, i, j) < current_no) {
2384 fprintf(stderr, "detected error [%d,%d] in %s at line %d\n", i, j, __FUNCTION__, __LINE__);
2386 sstate->solver_status = SOLVER_MISTAKE;
2389 if (4 - CLUE_AT(state, i, j) == current_no) {
2390 if (square_setall(sstate, i, j, LINE_UNKNOWN, LINE_YES))
2391 diff = min(diff, DIFF_EASY);
2392 sstate->square_solved[SQUARE_INDEX(state, i, j)] = TRUE;
2397 check_caches(sstate);
2399 /* Per-dot deductions */
2400 FORALL_DOTS(state, i, j) {
2401 if (sstate->dot_solved[DOT_INDEX(state, i, j)])
2404 switch (DOT_YES_COUNT(sstate, i, j)) {
2406 switch (DOT_NO_COUNT(sstate, i, j)) {
2409 fprintf(stderr, "dot [%d,%d]: 0 yes, 3 no\n", i, j);
2411 dot_setall(sstate, i, j, LINE_UNKNOWN, LINE_NO);
2412 diff = min(diff, DIFF_EASY);
2415 sstate->dot_solved[DOT_INDEX(state, i, j)] = TRUE;
2420 switch (DOT_NO_COUNT(sstate, i, j)) {
2421 case 2: /* 1 yes, 2 no */
2423 fprintf(stderr, "dot [%d,%d]: 1 yes, 2 no\n", i, j);
2425 dot_setall(sstate, i, j, LINE_UNKNOWN, LINE_YES);
2426 diff = min(diff, DIFF_EASY);
2427 sstate->dot_solved[DOT_INDEX(state, i, j)] = TRUE;
2429 case 3: /* 1 yes, 3 no */
2431 fprintf(stderr, "detected error [%d,%d] in %s at line %d\n", i, j, __FUNCTION__, __LINE__);
2433 sstate->solver_status = SOLVER_MISTAKE;
2439 fprintf(stderr, "dot [%d,%d]: 2 yes\n", i, j);
2441 dot_setall(sstate, i, j, LINE_UNKNOWN, LINE_NO);
2442 diff = min(diff, DIFF_EASY);
2443 sstate->dot_solved[DOT_INDEX(state, i, j)] = TRUE;
2448 fprintf(stderr, "detected error [%d,%d] in %s at line %d\n", i, j, __FUNCTION__, __LINE__);
2450 sstate->solver_status = SOLVER_MISTAKE;
2455 check_caches(sstate);
2460 static int normal_mode_deductions(solver_state *sstate)
2463 game_state *state = sstate->state;
2465 int diff = DIFF_MAX;
2467 FORALL_SQUARES(state, i, j) {
2468 if (sstate->square_solved[SQUARE_INDEX(state, i, j)])
2471 if (CLUE_AT(state, i, j) < 0)
2474 switch (CLUE_AT(state, i, j)) {
2477 fprintf(stderr, "clue [%d,%d] is 1, doing dline ops\n",
2480 FORALL_SQUARE_DLINES(dd) {
2481 /* At most one of any DLINE can be set */
2482 if (set_square_dline(state,
2483 sstate->normal->dot_atmostone,
2485 diff = min(diff, DIFF_NORMAL);
2488 if (get_square_dline(state,
2489 sstate->normal->dot_atleastone,
2491 /* This DLINE provides enough YESes to solve the clue */
2492 if (square_setboth_in_dline(sstate, OPP_DLINE(dd),
2494 diff = min(diff, DIFF_EASY);
2501 /* If at least one of one DLINE is set, at most one
2502 * of the opposing one is and vice versa */
2504 fprintf(stderr, "clue [%d,%d] is 2, doing dline ops\n",
2507 FORALL_SQUARE_DLINES(dd) {
2508 if (get_square_dline(state,
2509 sstate->normal->dot_atmostone,
2511 if (set_square_opp_dline(state,
2512 sstate->normal->dot_atleastone,
2514 diff = min(diff, DIFF_NORMAL);
2517 if (get_square_dline(state,
2518 sstate->normal->dot_atleastone,
2520 if (set_square_opp_dline(state,
2521 sstate->normal->dot_atmostone,
2523 diff = min(diff, DIFF_NORMAL);
2530 fprintf(stderr, "clue [%d,%d] is 3, doing dline ops\n",
2533 FORALL_SQUARE_DLINES(dd) {
2534 /* At least one of any DLINE must be set */
2535 if (set_square_dline(state,
2536 sstate->normal->dot_atleastone,
2538 diff = min(diff, DIFF_NORMAL);
2541 if (get_square_dline(state,
2542 sstate->normal->dot_atmostone,
2544 /* This DLINE provides enough NOs to solve the clue */
2545 if (square_setboth_in_dline(sstate, OPP_DLINE(dd),
2547 diff = min(diff, DIFF_EASY);
2555 check_caches(sstate);
2557 if (diff < DIFF_NORMAL)
2560 FORALL_DOTS(state, i, j) {
2561 if (sstate->dot_solved[DOT_INDEX(state, i, j)])
2565 text = game_text_format(state);
2566 fprintf(stderr, "-----------------\n%s", text);
2570 switch (DOT_YES_COUNT(sstate, i, j)) {
2572 switch (DOT_NO_COUNT(sstate, i, j)) {
2574 /* Make note that at most one of each unknown DLINE
2581 switch (DOT_NO_COUNT(sstate, i, j)) {
2583 /* 1 yes, 1 no, so exactly one of unknowns is
2586 fprintf(stderr, "dot [%d,%d]: 1 yes, 1 no\n", i, j);
2588 FORALL_DOT_DLINES(dd) {
2589 if (dline_both_unknown(state,
2591 if (set_dot_dline(state,
2592 sstate->normal->dot_atleastone,
2594 diff = min(diff, DIFF_NORMAL);
2602 fprintf(stderr, "dot [%d,%d]: 1 yes, 0 or 1 no\n", i, j);
2604 /* 1 yes, fewer than 2 no, so at most one of
2605 * unknowns is yes */
2606 FORALL_DOT_DLINES(dd) {
2607 if (dline_both_unknown(state,
2609 if (set_dot_dline(state,
2610 sstate->normal->dot_atmostone,
2612 diff = min(diff, DIFF_NORMAL);
2621 /* DLINE deductions that don't depend on the exact number of
2622 * LINE_YESs or LINE_NOs */
2624 /* If at least one of a dline in a dot is YES, at most one
2625 * of the opposite dline to that dot must be YES. */
2626 FORALL_DOT_DLINES(dd) {
2627 if (get_dot_dline(state,
2628 sstate->normal->dot_atleastone,
2630 if (set_dot_opp_dline(state,
2631 sstate->normal->dot_atmostone,
2633 diff = min(diff, DIFF_NORMAL);
2638 if (dot_collapse_dlines(sstate, i, j))
2639 diff = min(diff, DIFF_EASY);
2641 check_caches(sstate);
2646 static int hard_mode_deductions(solver_state *sstate)
2649 game_state *state = sstate->state;
2650 const int h=state->h, w=state->w;
2651 enum direction dir1, dir2;
2652 int can1, can2, inv1, inv2;
2653 int diff = DIFF_MAX;
2654 const struct dline *dl;
2657 FORALL_SQUARES(state, i, j) {
2658 if (sstate->square_solved[SQUARE_INDEX(state, i, j)])
2661 switch (CLUE_AT(state, i, j)) {
2666 if (square_setall_identical(sstate, i, j, LINE_NO))
2667 diff = min(diff, DIFF_EASY);
2670 if (square_setall_identical(sstate, i, j, LINE_YES))
2671 diff = min(diff, DIFF_EASY);
2675 if (SQUARE_YES_COUNT(sstate, i, j) +
2676 SQUARE_NO_COUNT(sstate, i, j) == 2) {
2677 /* There are exactly two unknown lines bordering this
2679 if (SQUARE_YES_COUNT(sstate, i, j) + 1 ==
2680 CLUE_AT(state, i, j)) {
2681 /* They must be different */
2682 if (square_relate_2_unknowns(sstate, i, j, TRUE))
2683 diff = min(diff, DIFF_HARD);
2688 check_caches(sstate);
2690 FORALL_DOTS(state, i, j) {
2691 if (DOT_YES_COUNT(sstate, i, j) == 1 &&
2692 DOT_NO_COUNT(sstate, i, j) == 1) {
2693 if (dot_relate_2_unknowns(sstate, i, j, TRUE))
2694 diff = min(diff, DIFF_HARD);
2698 if (DOT_YES_COUNT(sstate, i, j) == 0 &&
2699 DOT_NO_COUNT(sstate, i, j) == 2) {
2700 if (dot_relate_2_unknowns(sstate, i, j, FALSE))
2701 diff = min(diff, DIFF_HARD);
2706 /* If two lines into a dot are related, the other two lines into that dot
2707 * are related in the same way. */
2709 /* iter over points that aren't on edges */
2710 for (i = 1; i < w; ++i) {
2711 for (j = 1; j < h; ++j) {
2712 if (sstate->dot_solved[DOT_INDEX(state, i, j)])
2715 /* iter over directions */
2716 for (dir1 = 0; dir1 < 4; ++dir1) {
2717 for (dir2 = dir1+1; dir2 < 4; ++dir2) {
2718 /* canonify both lines */
2719 can1 = edsf_canonify
2720 (sstate->hard->linedsf,
2721 LINEDSF_INDEX(state, i, j, dir1),
2723 can2 = edsf_canonify
2724 (sstate->hard->linedsf,
2725 LINEDSF_INDEX(state, i, j, dir2),
2727 /* merge opposite lines */
2729 if (merge_lines(sstate,
2730 i, j, OPP_DIR(dir1),
2731 i, j, OPP_DIR(dir2),
2733 diff = min(diff, DIFF_HARD);
2741 /* If the state of a line is known, deduce the state of its canonical line
2743 FORALL_DOTS(state, i, j) {
2744 /* Do this even if the dot we're on is solved */
2746 can1 = edsf_canonify(sstate->hard->linedsf,
2747 LINEDSF_INDEX(state, i, j, RIGHT),
2749 linedsf_deindex(state, can1, &a, &b, &dir1);
2750 s = RIGHTOF_DOT(state, i, j);
2751 if (s != LINE_UNKNOWN)
2753 if (set_line_bydot(sstate, a, b, dir1, inv1 ? OPP(s) : s))
2754 diff = min(diff, DIFF_EASY);
2758 can1 = edsf_canonify(sstate->hard->linedsf,
2759 LINEDSF_INDEX(state, i, j, DOWN),
2761 linedsf_deindex(state, can1, &a, &b, &dir1);
2762 s = BELOW_DOT(state, i, j);
2763 if (s != LINE_UNKNOWN)
2765 if (set_line_bydot(sstate, a, b, dir1, inv1 ? OPP(s) : s))
2766 diff = min(diff, DIFF_EASY);
2771 /* Interactions between dline and linedsf */
2772 FORALL_DOTS(state, i, j) {
2773 if (sstate->dot_solved[DOT_INDEX(state, i, j)])
2776 FORALL_DOT_DLINES(dd) {
2778 if (i == 0 && (dl->dir1 == LEFT || dl->dir2 == LEFT))
2780 if (i == w && (dl->dir1 == RIGHT || dl->dir2 == RIGHT))
2782 if (j == 0 && (dl->dir1 == UP || dl->dir2 == UP))
2784 if (j == h && (dl->dir1 == DOWN || dl->dir2 == DOWN))
2787 if (get_dot_dline(state, sstate->normal->dot_atleastone,
2789 get_dot_dline(state, sstate->normal->dot_atmostone,
2791 /* atleastone && atmostone => inverse */
2792 if (merge_lines(sstate, i, j, dl->dir1, i, j, dl->dir2, 1)) {
2793 diff = min(diff, DIFF_HARD);
2796 /* don't have atleastone and atmostone for this dline */
2797 can1 = edsf_canonify(sstate->hard->linedsf,
2798 LINEDSF_INDEX(state, i, j, dl->dir1),
2800 can2 = edsf_canonify(sstate->hard->linedsf,
2801 LINEDSF_INDEX(state, i, j, dl->dir2),
2805 /* identical => collapse dline */
2806 if (get_dot_dline(state,
2807 sstate->normal->dot_atleastone,
2809 if (set_line_bydot(sstate, i, j,
2810 dl->dir1, LINE_YES)) {
2811 diff = min(diff, DIFF_EASY);
2813 if (set_line_bydot(sstate, i, j,
2814 dl->dir2, LINE_YES)) {
2815 diff = min(diff, DIFF_EASY);
2817 } else if (get_dot_dline(state,
2818 sstate->normal->dot_atmostone,
2820 if (set_line_bydot(sstate, i, j,
2821 dl->dir1, LINE_NO)) {
2822 diff = min(diff, DIFF_EASY);
2824 if (set_line_bydot(sstate, i, j,
2825 dl->dir2, LINE_NO)) {
2826 diff = min(diff, DIFF_EASY);
2830 /* inverse => atleastone && atmostone */
2831 if (set_dot_dline(state,
2832 sstate->normal->dot_atleastone,
2834 diff = min(diff, DIFF_NORMAL);
2836 if (set_dot_dline(state,
2837 sstate->normal->dot_atmostone,
2839 diff = min(diff, DIFF_NORMAL);
2847 /* If the state of the canonical line for line 'l' is known, deduce the
2849 FORALL_DOTS(state, i, j) {
2850 if (sstate->dot_solved[DOT_INDEX(state, i, j)])
2854 can1 = edsf_canonify(sstate->hard->linedsf,
2855 LINEDSF_INDEX(state, i, j, RIGHT),
2857 linedsf_deindex(state, can1, &a, &b, &dir1);
2858 s = get_line_status_from_point(state, a, b, dir1);
2859 if (s != LINE_UNKNOWN)
2861 if (set_line_bydot(sstate, i, j, RIGHT, inv1 ? OPP(s) : s))
2862 diff = min(diff, DIFF_EASY);
2866 can1 = edsf_canonify(sstate->hard->linedsf,
2867 LINEDSF_INDEX(state, i, j, DOWN),
2869 linedsf_deindex(state, can1, &a, &b, &dir1);
2870 s = get_line_status_from_point(state, a, b, dir1);
2871 if (s != LINE_UNKNOWN)
2873 if (set_line_bydot(sstate, i, j, DOWN, inv1 ? OPP(s) : s))
2874 diff = min(diff, DIFF_EASY);
2882 static int loop_deductions(solver_state *sstate)
2884 int edgecount = 0, clues = 0, satclues = 0, sm1clues = 0;
2885 game_state *state = sstate->state;
2886 int shortest_chainlen = DOT_COUNT(state);
2887 int loop_found = FALSE;
2890 int progress = FALSE;
2894 * Go through the grid and update for all the new edges.
2895 * Since merge_dots() is idempotent, the simplest way to
2896 * do this is just to update for _all_ the edges.
2898 * Also, while we're here, we count the edges, count the
2899 * clues, count the satisfied clues, and count the
2900 * satisfied-minus-one clues.
2902 FORALL_DOTS(state, i, j) {
2903 if (RIGHTOF_DOT(state, i, j) == LINE_YES) {
2904 loop_found |= merge_dots(sstate, i, j, i+1, j);
2907 if (BELOW_DOT(state, i, j) == LINE_YES) {
2908 loop_found |= merge_dots(sstate, i, j, i, j+1);
2912 if (CLUE_AT(state, i, j) >= 0) {
2913 int c = CLUE_AT(state, i, j);
2914 int o = SQUARE_YES_COUNT(sstate, i, j);
2923 for (i = 0; i < DOT_COUNT(state); ++i) {
2925 sstate->looplen[dsf_canonify(sstate->dotdsf, i)];
2926 if (dots_connected > 1)
2927 shortest_chainlen = min(shortest_chainlen, dots_connected);
2930 assert(sstate->solver_status == SOLVER_INCOMPLETE);
2932 if (satclues == clues && shortest_chainlen == edgecount) {
2933 sstate->solver_status = SOLVER_SOLVED;
2934 /* This discovery clearly counts as progress, even if we haven't
2935 * just added any lines or anything */
2937 goto finished_loop_deductionsing;
2941 * Now go through looking for LINE_UNKNOWN edges which
2942 * connect two dots that are already in the same
2943 * equivalence class. If we find one, test to see if the
2944 * loop it would create is a solution.
2946 FORALL_DOTS(state, i, j) {
2947 for (d = 0; d < 2; d++) {
2948 int i2, j2, eqclass, val;
2951 if (RIGHTOF_DOT(state, i, j) !=
2957 if (BELOW_DOT(state, i, j) !=
2965 eqclass = dsf_canonify(sstate->dotdsf, j * (state->w+1) + i);
2966 if (eqclass != dsf_canonify(sstate->dotdsf,
2967 j2 * (state->w+1) + i2)) {
2971 val = LINE_NO; /* loop is bad until proven otherwise */
2974 * This edge would form a loop. Next
2975 * question: how long would the loop be?
2976 * Would it equal the total number of edges
2977 * (plus the one we'd be adding if we added
2980 if (sstate->looplen[eqclass] == edgecount + 1) {
2985 * This edge would form a loop which
2986 * took in all the edges in the entire
2987 * grid. So now we need to work out
2988 * whether it would be a valid solution
2989 * to the puzzle, which means we have to
2990 * check if it satisfies all the clues.
2991 * This means that every clue must be
2992 * either satisfied or satisfied-minus-
2993 * 1, and also that the number of
2994 * satisfied-minus-1 clues must be at
2995 * most two and they must lie on either
2996 * side of this edge.
3001 if (CLUE_AT(state, cx,cy) >= 0 &&
3002 square_order(state, cx,cy, LINE_YES) ==
3003 CLUE_AT(state, cx,cy) - 1) {
3006 if (CLUE_AT(state, i, j) >= 0 &&
3007 SQUARE_YES_COUNT(sstate, i, j) ==
3008 CLUE_AT(state, i, j) - 1) {
3011 if (sm1clues == sm1_nearby &&
3012 sm1clues + satclues == clues) {
3013 val = LINE_YES; /* loop is good! */
3018 * Right. Now we know that adding this edge
3019 * would form a loop, and we know whether
3020 * that loop would be a viable solution or
3023 * If adding this edge produces a solution,
3024 * then we know we've found _a_ solution but
3025 * we don't know that it's _the_ solution -
3026 * if it were provably the solution then
3027 * we'd have deduced this edge some time ago
3028 * without the need to do loop detection. So
3029 * in this state we return SOLVER_AMBIGUOUS,
3030 * which has the effect that hitting Solve
3031 * on a user-provided puzzle will fill in a
3032 * solution but using the solver to
3033 * construct new puzzles won't consider this
3034 * a reasonable deduction for the user to
3038 progress = set_line_bydot(sstate, i, j, RIGHT, val);
3039 assert(progress == TRUE);
3041 progress = set_line_bydot(sstate, i, j, DOWN, val);
3042 assert(progress == TRUE);
3044 if (val == LINE_YES) {
3045 sstate->solver_status = SOLVER_AMBIGUOUS;
3046 goto finished_loop_deductionsing;
3051 finished_loop_deductionsing:
3052 return progress ? DIFF_EASY : DIFF_MAX;
3055 /* This will return a dynamically allocated solver_state containing the (more)
3057 static solver_state *solve_game_rec(const solver_state *sstate_start,
3062 solver_state *sstate, *sstate_saved, *sstate_tmp;
3063 solver_state *sstate_rec_solved;
3064 int recursive_soln_count;
3065 int solver_progress;
3068 /* Indicates which solver we should call next. This is a sensible starting
3070 int current_solver = DIFF_EASY, next_solver;
3076 printf("solve_game_rec: recursion_remaining = %d\n",
3077 sstate_start->recursion_remaining);
3080 sstate = dup_solver_state(sstate_start);
3082 /* Cache the values of some variables for readability */
3083 state = sstate->state;
3087 sstate_saved = NULL;
3089 nonrecursive_solver:
3090 solver_progress = FALSE;
3092 check_caches(sstate);
3096 text = game_text_format(state);
3097 fprintf(stderr, "-----------------\n%s", text);
3101 if (sstate->solver_status == SOLVER_MISTAKE)
3104 /* fprintf(stderr, "Invoking solver %d\n", current_solver); */
3105 next_solver = solver_fns[current_solver](sstate);
3107 if (next_solver == DIFF_MAX) {
3108 /* fprintf(stderr, "Current solver failed\n"); */
3109 if (current_solver < diff && current_solver + 1 < DIFF_MAX) {
3110 /* Try next beefier solver */
3111 next_solver = current_solver + 1;
3113 /* fprintf(stderr, "Doing loop deductions\n"); */
3114 next_solver = loop_deductions(sstate);
3118 if (sstate->solver_status == SOLVER_SOLVED ||
3119 sstate->solver_status == SOLVER_AMBIGUOUS) {
3120 /* fprintf(stderr, "Solver completed\n"); */
3124 /* Once we've looped over all permitted solvers then the loop
3125 * deductions without making any progress, we'll exit this while loop */
3126 current_solver = next_solver;
3127 } while (current_solver < DIFF_MAX);
3129 if (sstate->solver_status == SOLVER_SOLVED ||
3130 sstate->solver_status == SOLVER_AMBIGUOUS) {
3131 /* s/LINE_UNKNOWN/LINE_NO/g */
3132 array_setall(sstate->state->hl, LINE_UNKNOWN, LINE_NO,
3133 HL_COUNT(sstate->state));
3134 array_setall(sstate->state->vl, LINE_UNKNOWN, LINE_NO,
3135 VL_COUNT(sstate->state));
3139 /* Perform recursive calls */
3140 if (sstate->recursion_remaining) {
3141 sstate_saved = dup_solver_state(sstate);
3143 sstate->recursion_remaining--;
3145 recursive_soln_count = 0;
3146 sstate_rec_solved = NULL;
3148 /* Memory management:
3149 * sstate_saved won't be modified but needs to be freed when we have
3151 * sstate is expected to contain our 'best' solution by the time we
3152 * finish this section of code. It's the thing we'll try adding lines
3153 * to, seeing if they make it more solvable.
3154 * If sstate_rec_solved is non-NULL, it will supersede sstate
3155 * eventually. sstate_tmp should not hold a value persistently.
3158 /* NB SOLVER_AMBIGUOUS is like SOLVER_SOLVED except the solver is aware
3159 * of the possibility of additional solutions. So as soon as we have a
3160 * SOLVER_AMBIGUOUS we can safely propagate it back to our caller, but
3161 * if we get a SOLVER_SOLVED we want to keep trying in case we find
3162 * further solutions and have to mark it ambiguous.
3165 #define DO_RECURSIVE_CALL(dir_dot) \
3166 if (dir_dot(sstate->state, i, j) == LINE_UNKNOWN) { \
3167 debug(("Trying " #dir_dot " at [%d,%d]\n", i, j)); \
3168 LV_##dir_dot(sstate->state, i, j) = LINE_YES; \
3169 sstate_tmp = solve_game_rec(sstate, diff); \
3170 switch (sstate_tmp->solver_status) { \
3171 case SOLVER_AMBIGUOUS: \
3172 debug(("Solver ambiguous, returning\n")); \
3173 sstate_rec_solved = sstate_tmp; \
3174 goto finished_recursion; \
3175 case SOLVER_SOLVED: \
3176 switch (++recursive_soln_count) { \
3178 debug(("One solution found\n")); \
3179 sstate_rec_solved = sstate_tmp; \
3182 debug(("Ambiguous solutions found\n")); \
3183 free_solver_state(sstate_tmp); \
3184 sstate_rec_solved->solver_status = SOLVER_AMBIGUOUS; \
3185 goto finished_recursion; \
3187 assert(!"recursive_soln_count out of range"); \
3191 case SOLVER_MISTAKE: \
3192 debug(("Non-solution found\n")); \
3193 free_solver_state(sstate_tmp); \
3194 free_solver_state(sstate_saved); \
3195 LV_##dir_dot(sstate->state, i, j) = LINE_NO; \
3196 goto nonrecursive_solver; \
3197 case SOLVER_INCOMPLETE: \
3198 debug(("Recursive step inconclusive\n")); \
3199 free_solver_state(sstate_tmp); \
3202 free_solver_state(sstate); \
3203 sstate = dup_solver_state(sstate_saved); \
3206 FORALL_DOTS(state, i, j) {
3207 /* Only perform recursive calls on 'loose ends' */
3208 if (DOT_YES_COUNT(sstate, i, j) == 1) {
3209 DO_RECURSIVE_CALL(LEFTOF_DOT);
3210 DO_RECURSIVE_CALL(RIGHTOF_DOT);
3211 DO_RECURSIVE_CALL(ABOVE_DOT);
3212 DO_RECURSIVE_CALL(BELOW_DOT);
3218 if (sstate_rec_solved) {
3219 free_solver_state(sstate);
3220 sstate = sstate_rec_solved;
3228 #define HANDLE_DLINE(dline, dir1_sq, dir2_sq, a, b) \
3229 if (sstate->normal->dot_atmostone[i+a + (sstate->state->w + 1) * (j+b)] & \
3231 if (square_order(sstate->state, i, j, LINE_UNKNOWN) - 1 == \
3232 CLUE_AT(sstate->state, i, j) - '0') { \
3233 square_setall(sstate->state, i, j, LINE_UNKNOWN, LINE_YES); \
3234 /* XXX the following may overwrite known data! */ \
3235 dir1_sq(sstate->state, i, j) = LINE_UNKNOWN; \
3236 dir2_sq(sstate->state, i, j) = LINE_UNKNOWN; \
3243 static char *solve_game(game_state *state, game_state *currstate,
3244 char *aux, char **error)
3247 solver_state *sstate, *new_sstate;
3249 sstate = new_solver_state(state, DIFF_MAX);
3250 new_sstate = solve_game_rec(sstate, DIFF_MAX);
3252 if (new_sstate->solver_status == SOLVER_SOLVED) {
3253 soln = encode_solve_move(new_sstate->state);
3254 } else if (new_sstate->solver_status == SOLVER_AMBIGUOUS) {
3255 soln = encode_solve_move(new_sstate->state);
3256 /**error = "Solver found ambiguous solutions"; */
3258 soln = encode_solve_move(new_sstate->state);
3259 /**error = "Solver failed"; */
3262 free_solver_state(new_sstate);
3263 free_solver_state(sstate);
3268 /* ----------------------------------------------------------------------
3269 * Drawing and mouse-handling
3272 static char *interpret_move(game_state *state, game_ui *ui, game_drawstate *ds,
3273 int x, int y, int button)
3278 char button_char = ' ';
3279 enum line_state old_state;
3281 button &= ~MOD_MASK;
3283 /* Around each line is a diamond-shaped region where points within that
3284 * region are closer to this line than any other. We assume any click
3285 * within a line's diamond was meant for that line. It would all be a lot
3286 * simpler if the / and % operators respected modulo arithmetic properly
3287 * for negative numbers. */
3292 /* Get the coordinates of the square the click was in */
3293 i = (x + TILE_SIZE) / TILE_SIZE - 1;
3294 j = (y + TILE_SIZE) / TILE_SIZE - 1;
3296 /* Get the precise position inside square [i,j] */
3297 p = (x + TILE_SIZE) % TILE_SIZE;
3298 q = (y + TILE_SIZE) % TILE_SIZE;
3300 /* After this bit of magic [i,j] will correspond to the point either above
3301 * or to the left of the line selected */
3303 if (TILE_SIZE - p > q) {
3306 hl_selected = FALSE;
3310 if (TILE_SIZE - q > p) {
3311 hl_selected = FALSE;
3322 if (i >= state->w || j >= state->h + 1)
3325 if (i >= state->w + 1 || j >= state->h)
3329 /* I think it's only possible to play this game with mouse clicks, sorry */
3330 /* Maybe will add mouse drag support some time */
3332 old_state = RIGHTOF_DOT(state, i, j);
3334 old_state = BELOW_DOT(state, i, j);
3338 switch (old_state) {
3352 switch (old_state) {
3367 sprintf(buf, "%d,%d%c%c", i, j, (int)(hl_selected ? 'h' : 'v'), (int)button_char);
3373 static game_state *execute_move(game_state *state, char *move)
3376 game_state *newstate = dup_game(state);
3378 if (move[0] == 'S') {
3380 newstate->cheated = TRUE;
3385 move = strchr(move, ',');
3389 move += strspn(move, "1234567890");
3390 switch (*(move++)) {
3392 if (i >= newstate->w || j > newstate->h)
3394 switch (*(move++)) {
3396 LV_RIGHTOF_DOT(newstate, i, j) = LINE_YES;
3399 LV_RIGHTOF_DOT(newstate, i, j) = LINE_NO;
3402 LV_RIGHTOF_DOT(newstate, i, j) = LINE_UNKNOWN;
3409 if (i > newstate->w || j >= newstate->h)
3411 switch (*(move++)) {
3413 LV_BELOW_DOT(newstate, i, j) = LINE_YES;
3416 LV_BELOW_DOT(newstate, i, j) = LINE_NO;
3419 LV_BELOW_DOT(newstate, i, j) = LINE_UNKNOWN;
3431 * Check for completion.
3433 i = 0; /* placate optimiser */
3434 for (j = 0; j <= newstate->h; j++) {
3435 for (i = 0; i < newstate->w; i++)
3436 if (LV_RIGHTOF_DOT(newstate, i, j) == LINE_YES)
3438 if (i < newstate->w)
3441 if (j <= newstate->h) {
3447 * We've found a horizontal edge at (i,j). Follow it round
3448 * to see if it's part of a loop.
3452 int order = dot_order(newstate, x, y, LINE_YES);
3454 goto completion_check_done;
3456 if (LEFTOF_DOT(newstate, x, y) == LINE_YES && prevdir != 'L') {
3459 } else if (RIGHTOF_DOT(newstate, x, y) == LINE_YES &&
3463 } else if (ABOVE_DOT(newstate, x, y) == LINE_YES &&
3467 } else if (BELOW_DOT(newstate, x, y) == LINE_YES &&
3472 assert(!"Can't happen"); /* dot_order guarantees success */
3477 if (x == i && y == j)
3481 if (x != i || y != j || looplen == 0)
3482 goto completion_check_done;
3485 * We've traced our way round a loop, and we know how many
3486 * line segments were involved. Count _all_ the line
3487 * segments in the grid, to see if the loop includes them
3491 FORALL_DOTS(newstate, i, j) {
3492 count += ((RIGHTOF_DOT(newstate, i, j) == LINE_YES) +
3493 (BELOW_DOT(newstate, i, j) == LINE_YES));
3495 assert(count >= looplen);
3496 if (count != looplen)
3497 goto completion_check_done;
3500 * The grid contains one closed loop and nothing else.
3501 * Check that all the clues are satisfied.
3503 FORALL_SQUARES(newstate, i, j) {
3504 if (CLUE_AT(newstate, i, j) >= 0) {
3505 if (square_order(newstate, i, j, LINE_YES) !=
3506 CLUE_AT(newstate, i, j)) {
3507 goto completion_check_done;
3515 newstate->solved = TRUE;
3518 completion_check_done:
3522 free_game(newstate);
3526 /* ----------------------------------------------------------------------
3529 static void game_redraw(drawing *dr, game_drawstate *ds, game_state *oldstate,
3530 game_state *state, int dir, game_ui *ui,
3531 float animtime, float flashtime)
3535 int line_colour, flash_changed;
3540 * The initial contents of the window are not guaranteed and
3541 * can vary with front ends. To be on the safe side, all games
3542 * should start by drawing a big background-colour rectangle
3543 * covering the whole window.
3545 draw_rect(dr, 0, 0, SIZE(state->w), SIZE(state->h), COL_BACKGROUND);
3548 FORALL_DOTS(state, i, j) {
3550 BORDER + i * TILE_SIZE - LINEWIDTH/2,
3551 BORDER + j * TILE_SIZE - LINEWIDTH/2,
3552 LINEWIDTH, LINEWIDTH, COL_FOREGROUND);
3556 FORALL_SQUARES(state, i, j) {
3557 c[0] = CLUE2CHAR(CLUE_AT(state, i, j));
3560 BORDER + i * TILE_SIZE + TILE_SIZE/2,
3561 BORDER + j * TILE_SIZE + TILE_SIZE/2,
3562 FONT_VARIABLE, TILE_SIZE/2,
3563 ALIGN_VCENTRE | ALIGN_HCENTRE, COL_FOREGROUND, c);
3565 draw_update(dr, 0, 0,
3566 state->w * TILE_SIZE + 2*BORDER + 1,
3567 state->h * TILE_SIZE + 2*BORDER + 1);
3571 if (flashtime > 0 &&
3572 (flashtime <= FLASH_TIME/3 ||
3573 flashtime >= FLASH_TIME*2/3)) {
3574 flash_changed = !ds->flashing;
3575 ds->flashing = TRUE;
3576 line_colour = COL_HIGHLIGHT;
3578 flash_changed = ds->flashing;
3579 ds->flashing = FALSE;
3580 line_colour = COL_FOREGROUND;
3583 #define CROSS_SIZE (3 * LINEWIDTH / 2)
3585 /* Redraw clue colours if necessary */
3586 FORALL_SQUARES(state, i, j) {
3587 n = CLUE_AT(state, i, j);
3591 assert(n >= 0 && n <= 4);
3593 c[0] = CLUE2CHAR(CLUE_AT(state, i, j));
3596 clue_mistake = (square_order(state, i, j, LINE_YES) > n ||
3597 square_order(state, i, j, LINE_NO ) > (4-n));
3599 if (clue_mistake != ds->clue_error[SQUARE_INDEX(state, i, j)]) {
3601 BORDER + i * TILE_SIZE + CROSS_SIZE,
3602 BORDER + j * TILE_SIZE + CROSS_SIZE,
3603 TILE_SIZE - CROSS_SIZE * 2, TILE_SIZE - CROSS_SIZE * 2,
3606 BORDER + i * TILE_SIZE + TILE_SIZE/2,
3607 BORDER + j * TILE_SIZE + TILE_SIZE/2,
3608 FONT_VARIABLE, TILE_SIZE/2,
3609 ALIGN_VCENTRE | ALIGN_HCENTRE,
3610 clue_mistake ? COL_MISTAKE : COL_FOREGROUND, c);
3611 draw_update(dr, i * TILE_SIZE + BORDER, j * TILE_SIZE + BORDER,
3612 TILE_SIZE, TILE_SIZE);
3614 ds->clue_error[SQUARE_INDEX(state, i, j)] = clue_mistake;
3618 /* I've also had a request to colour lines red if they make a non-solution
3619 * loop, or if more than two lines go into any point. I think that would
3620 * be good some time. */
3622 #define CLEAR_VL(i, j) \
3625 BORDER + i * TILE_SIZE - CROSS_SIZE, \
3626 BORDER + j * TILE_SIZE + LINEWIDTH - LINEWIDTH/2, \
3628 TILE_SIZE - LINEWIDTH, \
3631 BORDER + i * TILE_SIZE - CROSS_SIZE, \
3632 BORDER + j * TILE_SIZE - CROSS_SIZE, \
3634 TILE_SIZE + CROSS_SIZE*2); \
3637 #define CLEAR_HL(i, j) \
3640 BORDER + i * TILE_SIZE + LINEWIDTH - LINEWIDTH/2, \
3641 BORDER + j * TILE_SIZE - CROSS_SIZE, \
3642 TILE_SIZE - LINEWIDTH, \
3646 BORDER + i * TILE_SIZE - CROSS_SIZE, \
3647 BORDER + j * TILE_SIZE - CROSS_SIZE, \
3648 TILE_SIZE + CROSS_SIZE*2, \
3652 /* Vertical lines */
3653 FORALL_VL(state, i, j) {
3654 switch (BELOW_DOT(state, i, j)) {
3656 if (ds->vl[VL_INDEX(state, i, j)] != BELOW_DOT(state, i, j)) {
3661 if (ds->vl[VL_INDEX(state, i, j)] != BELOW_DOT(state, i, j) ||
3665 BORDER + i * TILE_SIZE - LINEWIDTH/2,
3666 BORDER + j * TILE_SIZE + LINEWIDTH - LINEWIDTH/2,
3667 LINEWIDTH, TILE_SIZE - LINEWIDTH,
3672 if (ds->vl[VL_INDEX(state, i, j)] != BELOW_DOT(state, i, j)) {
3675 BORDER + i * TILE_SIZE - CROSS_SIZE,
3676 BORDER + j * TILE_SIZE + TILE_SIZE/2 - CROSS_SIZE,
3677 BORDER + i * TILE_SIZE + CROSS_SIZE - 1,
3678 BORDER + j * TILE_SIZE + TILE_SIZE/2 + CROSS_SIZE - 1,
3681 BORDER + i * TILE_SIZE + CROSS_SIZE - 1,
3682 BORDER + j * TILE_SIZE + TILE_SIZE/2 - CROSS_SIZE,
3683 BORDER + i * TILE_SIZE - CROSS_SIZE,
3684 BORDER + j * TILE_SIZE + TILE_SIZE/2 + CROSS_SIZE - 1,
3689 ds->vl[VL_INDEX(state, i, j)] = BELOW_DOT(state, i, j);
3692 /* Horizontal lines */
3693 FORALL_HL(state, i, j) {
3694 switch (RIGHTOF_DOT(state, i, j)) {
3696 if (ds->hl[HL_INDEX(state, i, j)] != RIGHTOF_DOT(state, i, j)) {
3701 if (ds->hl[HL_INDEX(state, i, j)] != RIGHTOF_DOT(state, i, j) ||
3705 BORDER + i * TILE_SIZE + LINEWIDTH - LINEWIDTH/2,
3706 BORDER + j * TILE_SIZE - LINEWIDTH/2,
3707 TILE_SIZE - LINEWIDTH, LINEWIDTH,
3712 if (ds->hl[HL_INDEX(state, i, j)] != RIGHTOF_DOT(state, i, j)) {
3715 BORDER + i * TILE_SIZE + TILE_SIZE/2 - CROSS_SIZE,
3716 BORDER + j * TILE_SIZE + CROSS_SIZE - 1,
3717 BORDER + i * TILE_SIZE + TILE_SIZE/2 + CROSS_SIZE - 1,
3718 BORDER + j * TILE_SIZE - CROSS_SIZE,
3721 BORDER + i * TILE_SIZE + TILE_SIZE/2 - CROSS_SIZE,
3722 BORDER + j * TILE_SIZE - CROSS_SIZE,
3723 BORDER + i * TILE_SIZE + TILE_SIZE/2 + CROSS_SIZE - 1,
3724 BORDER + j * TILE_SIZE + CROSS_SIZE - 1,
3729 ds->hl[HL_INDEX(state, i, j)] = RIGHTOF_DOT(state, i, j);
3733 static float game_flash_length(game_state *oldstate, game_state *newstate,
3734 int dir, game_ui *ui)
3736 if (!oldstate->solved && newstate->solved &&
3737 !oldstate->cheated && !newstate->cheated) {
3744 static void game_print_size(game_params *params, float *x, float *y)
3749 * I'll use 7mm squares by default.
3751 game_compute_size(params, 700, &pw, &ph);
3756 static void game_print(drawing *dr, game_state *state, int tilesize)
3758 int ink = print_mono_colour(dr, 0);
3760 game_drawstate ads, *ds = &ads;
3762 game_set_size(dr, ds, NULL, tilesize);
3765 * Dots. I'll deliberately make the dots a bit wider than the
3766 * lines, so you can still see them. (And also because it's
3767 * annoyingly tricky to make them _exactly_ the same size...)
3769 FORALL_DOTS(state, x, y) {
3770 draw_circle(dr, BORDER + x * TILE_SIZE, BORDER + y * TILE_SIZE,
3771 LINEWIDTH, ink, ink);
3777 FORALL_SQUARES(state, x, y) {
3778 if (CLUE_AT(state, x, y) >= 0) {
3781 c[0] = CLUE2CHAR(CLUE_AT(state, x, y));
3784 BORDER + x * TILE_SIZE + TILE_SIZE/2,
3785 BORDER + y * TILE_SIZE + TILE_SIZE/2,
3786 FONT_VARIABLE, TILE_SIZE/2,
3787 ALIGN_VCENTRE | ALIGN_HCENTRE, ink, c);
3792 * Lines. (At the moment, I'm not bothering with crosses.)
3794 FORALL_HL(state, x, y) {
3795 if (RIGHTOF_DOT(state, x, y) == LINE_YES)
3796 draw_rect(dr, BORDER + x * TILE_SIZE,
3797 BORDER + y * TILE_SIZE - LINEWIDTH/2,
3798 TILE_SIZE, (LINEWIDTH/2) * 2 + 1, ink);
3801 FORALL_VL(state, x, y) {
3802 if (BELOW_DOT(state, x, y) == LINE_YES)
3803 draw_rect(dr, BORDER + x * TILE_SIZE - LINEWIDTH/2,
3804 BORDER + y * TILE_SIZE,
3805 (LINEWIDTH/2) * 2 + 1, TILE_SIZE, ink);
3810 #define thegame loopy
3813 const struct game thegame = {
3814 "Loopy", "games.loopy", "loopy",
3821 TRUE, game_configure, custom_params,
3829 TRUE, game_text_format,
3837 PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
3840 game_free_drawstate,
3844 TRUE, FALSE, game_print_size, game_print,
3845 FALSE /* wants_statusbar */,
3846 FALSE, game_timing_state,
3847 0, /* mouse_priorities */