4 * An implementation of the Nikoli game 'Loop the loop'.
5 * (c) Mike Pinna, 2005, 2006
6 * Substantially rewritten to allowing for more general types of grid.
7 * (c) Lambros Lambrou 2008
9 * vim: set shiftwidth=4 :set textwidth=80:
13 * Possible future solver enhancements:
15 * - There's an interesting deductive technique which makes use
16 * of topology rather than just graph theory. Each _face_ in
17 * the grid is either inside or outside the loop; you can tell
18 * that two faces are on the same side of the loop if they're
19 * separated by a LINE_NO (or, more generally, by a path
20 * crossing no LINE_UNKNOWNs and an even number of LINE_YESes),
21 * and on the opposite side of the loop if they're separated by
22 * a LINE_YES (or an odd number of LINE_YESes and no
23 * LINE_UNKNOWNs). Oh, and any face separated from the outside
24 * of the grid by a LINE_YES or a LINE_NO is on the inside or
25 * outside respectively. So if you can track this for all
26 * faces, you figure out the state of the line between a pair
27 * once their relative insideness is known.
28 * + The way I envisage this working is simply to keep an edsf
29 * of all _faces_, which indicates whether they're on
30 * opposite sides of the loop from one another. We also
31 * include a special entry in the edsf for the infinite
33 * + So, the simple way to do this is to just go through the
34 * edges: every time we see an edge in a state other than
35 * LINE_UNKNOWN which separates two faces that aren't in the
36 * same edsf class, we can rectify that by merging the
37 * classes. Then, conversely, an edge in LINE_UNKNOWN state
38 * which separates two faces that _are_ in the same edsf
39 * class can immediately have its state determined.
40 * + But you can go one better, if you're prepared to loop
41 * over all _pairs_ of edges. Suppose we have edges A and B,
42 * which respectively separate faces A1,A2 and B1,B2.
43 * Suppose that A,B are in the same edge-edsf class and that
44 * A1,B1 (wlog) are in the same face-edsf class; then we can
45 * immediately place A2,B2 into the same face-edsf class (as
46 * each other, not as A1 and A2) one way round or the other.
47 * And conversely again, if A1,B1 are in the same face-edsf
48 * class and so are A2,B2, then we can put A,B into the same
50 * * Of course, this deduction requires a quadratic-time
51 * loop over all pairs of edges in the grid, so it should
52 * be reserved until there's nothing easier left to be
55 * - The generalised grid support has made me (SGT) notice a
56 * possible extension to the loop-avoidance code. When you have
57 * a path of connected edges such that no other edges at all
58 * are incident on any vertex in the middle of the path - or,
59 * alternatively, such that any such edges are already known to
60 * be LINE_NO - then you know those edges are either all
61 * LINE_YES or all LINE_NO. Hence you can mentally merge the
62 * entire path into a single long curly edge for the purposes
63 * of loop avoidance, and look directly at whether or not the
64 * extreme endpoints of the path are connected by some other
65 * route. I find this coming up fairly often when I play on the
66 * octagonal grid setting, so it might be worth implementing in
69 * - (Just a speed optimisation.) Consider some todo list queue where every
70 * time we modify something we mark it for consideration by other bits of
71 * the solver, to save iteration over things that have already been done.
87 /* Debugging options */
95 /* ----------------------------------------------------------------------
96 * Struct, enum and function declarations
111 grid *game_grid; /* ref-counted (internally) */
113 /* Put -1 in a face that doesn't get a clue */
116 /* Array of line states, to store whether each line is
117 * YES, NO or UNKNOWN */
120 unsigned char *line_errors;
121 int exactly_one_loop;
126 /* Used in game_text_format(), so that it knows what type of
127 * grid it's trying to render as ASCII text. */
132 SOLVER_SOLVED, /* This is the only solution the solver could find */
133 SOLVER_MISTAKE, /* This is definitely not a solution */
134 SOLVER_AMBIGUOUS, /* This _might_ be an ambiguous solution */
135 SOLVER_INCOMPLETE /* This may be a partial solution */
138 /* ------ Solver state ------ */
139 typedef struct solver_state {
141 enum solver_status solver_status;
142 /* NB looplen is the number of dots that are joined together at a point, ie a
143 * looplen of 1 means there are no lines to a particular dot */
146 /* Difficulty level of solver. Used by solver functions that want to
147 * vary their behaviour depending on the requested difficulty level. */
153 char *face_yes_count;
155 char *dot_solved, *face_solved;
158 /* Information for Normal level deductions:
159 * For each dline, store a bitmask for whether we know:
160 * (bit 0) at least one is YES
161 * (bit 1) at most one is YES */
164 /* Hard level information */
169 * Difficulty levels. I do some macro ickery here to ensure that my
170 * enum and the various forms of my name list always match up.
173 #define DIFFLIST(A) \
178 #define ENUM(upper,title,lower) DIFF_ ## upper,
179 #define TITLE(upper,title,lower) #title,
180 #define ENCODE(upper,title,lower) #lower
181 #define CONFIG(upper,title,lower) ":" #title
182 enum { DIFFLIST(ENUM) DIFF_MAX };
183 static char const *const diffnames[] = { DIFFLIST(TITLE) };
184 static char const diffchars[] = DIFFLIST(ENCODE);
185 #define DIFFCONFIG DIFFLIST(CONFIG)
188 * Solver routines, sorted roughly in order of computational cost.
189 * The solver will run the faster deductions first, and slower deductions are
190 * only invoked when the faster deductions are unable to make progress.
191 * Each function is associated with a difficulty level, so that the generated
192 * puzzles are solvable by applying only the functions with the chosen
193 * difficulty level or lower.
195 #define SOLVERLIST(A) \
196 A(trivial_deductions, DIFF_EASY) \
197 A(dline_deductions, DIFF_NORMAL) \
198 A(linedsf_deductions, DIFF_HARD) \
199 A(loop_deductions, DIFF_EASY)
200 #define SOLVER_FN_DECL(fn,diff) static int fn(solver_state *);
201 #define SOLVER_FN(fn,diff) &fn,
202 #define SOLVER_DIFF(fn,diff) diff,
203 SOLVERLIST(SOLVER_FN_DECL)
204 static int (*(solver_fns[]))(solver_state *) = { SOLVERLIST(SOLVER_FN) };
205 static int const solver_diffs[] = { SOLVERLIST(SOLVER_DIFF) };
206 static const int NUM_SOLVERS = sizeof(solver_diffs)/sizeof(*solver_diffs);
214 /* line_drawstate is the same as line_state, but with the extra ERROR
215 * possibility. The drawing code copies line_state to line_drawstate,
216 * except in the case that the line is an error. */
217 enum line_state { LINE_YES, LINE_UNKNOWN, LINE_NO };
218 enum line_drawstate { DS_LINE_YES, DS_LINE_UNKNOWN,
219 DS_LINE_NO, DS_LINE_ERROR };
221 #define OPP(line_state) \
225 struct game_drawstate {
232 char *clue_satisfied;
235 static char *validate_desc(const game_params *params, const char *desc);
236 static int dot_order(const game_state* state, int i, char line_type);
237 static int face_order(const game_state* state, int i, char line_type);
238 static solver_state *solve_game_rec(const solver_state *sstate);
241 static void check_caches(const solver_state* sstate);
243 #define check_caches(s)
246 /* ------- List of grid generators ------- */
247 #define GRIDLIST(A) \
248 A(Squares,GRID_SQUARE,3,3) \
249 A(Triangular,GRID_TRIANGULAR,3,3) \
250 A(Honeycomb,GRID_HONEYCOMB,3,3) \
251 A(Snub-Square,GRID_SNUBSQUARE,3,3) \
252 A(Cairo,GRID_CAIRO,3,4) \
253 A(Great-Hexagonal,GRID_GREATHEXAGONAL,3,3) \
254 A(Octagonal,GRID_OCTAGONAL,3,3) \
255 A(Kites,GRID_KITE,3,3) \
256 A(Floret,GRID_FLORET,1,2) \
257 A(Dodecagonal,GRID_DODECAGONAL,2,2) \
258 A(Great-Dodecagonal,GRID_GREATDODECAGONAL,2,2) \
259 A(Penrose (kite/dart),GRID_PENROSE_P2,3,3) \
260 A(Penrose (rhombs),GRID_PENROSE_P3,3,3)
262 #define GRID_NAME(title,type,amin,omin) #title,
263 #define GRID_CONFIG(title,type,amin,omin) ":" #title
264 #define GRID_TYPE(title,type,amin,omin) type,
265 #define GRID_SIZES(title,type,amin,omin) \
267 "Width and height for this grid type must both be at least " #amin, \
268 "At least one of width and height for this grid type must be at least " #omin,},
269 static char const *const gridnames[] = { GRIDLIST(GRID_NAME) };
270 #define GRID_CONFIGS GRIDLIST(GRID_CONFIG)
271 static grid_type grid_types[] = { GRIDLIST(GRID_TYPE) };
272 #define NUM_GRID_TYPES (sizeof(grid_types) / sizeof(grid_types[0]))
273 static const struct {
276 } grid_size_limits[] = { GRIDLIST(GRID_SIZES) };
278 /* Generates a (dynamically allocated) new grid, according to the
279 * type and size requested in params. Does nothing if the grid is already
281 static grid *loopy_generate_grid(const game_params *params,
282 const char *grid_desc)
284 return grid_new(grid_types[params->type], params->w, params->h, grid_desc);
287 /* ----------------------------------------------------------------------
291 /* General constants */
292 #define PREFERRED_TILE_SIZE 32
293 #define BORDER(tilesize) ((tilesize) / 2)
294 #define FLASH_TIME 0.5F
296 #define BIT_SET(field, bit) ((field) & (1<<(bit)))
298 #define SET_BIT(field, bit) (BIT_SET(field, bit) ? FALSE : \
299 ((field) |= (1<<(bit)), TRUE))
301 #define CLEAR_BIT(field, bit) (BIT_SET(field, bit) ? \
302 ((field) &= ~(1<<(bit)), TRUE) : FALSE)
304 #define CLUE2CHAR(c) \
305 ((c < 0) ? ' ' : c < 10 ? c + '0' : c - 10 + 'A')
307 /* ----------------------------------------------------------------------
308 * General struct manipulation and other straightforward code
311 static game_state *dup_game(const game_state *state)
313 game_state *ret = snew(game_state);
315 ret->game_grid = state->game_grid;
316 ret->game_grid->refcount++;
318 ret->solved = state->solved;
319 ret->cheated = state->cheated;
321 ret->clues = snewn(state->game_grid->num_faces, signed char);
322 memcpy(ret->clues, state->clues, state->game_grid->num_faces);
324 ret->lines = snewn(state->game_grid->num_edges, char);
325 memcpy(ret->lines, state->lines, state->game_grid->num_edges);
327 ret->line_errors = snewn(state->game_grid->num_edges, unsigned char);
328 memcpy(ret->line_errors, state->line_errors, state->game_grid->num_edges);
329 ret->exactly_one_loop = state->exactly_one_loop;
331 ret->grid_type = state->grid_type;
335 static void free_game(game_state *state)
338 grid_free(state->game_grid);
341 sfree(state->line_errors);
346 static solver_state *new_solver_state(const game_state *state, int diff) {
348 int num_dots = state->game_grid->num_dots;
349 int num_faces = state->game_grid->num_faces;
350 int num_edges = state->game_grid->num_edges;
351 solver_state *ret = snew(solver_state);
353 ret->state = dup_game(state);
355 ret->solver_status = SOLVER_INCOMPLETE;
358 ret->dotdsf = snew_dsf(num_dots);
359 ret->looplen = snewn(num_dots, int);
361 for (i = 0; i < num_dots; i++) {
365 ret->dot_solved = snewn(num_dots, char);
366 ret->face_solved = snewn(num_faces, char);
367 memset(ret->dot_solved, FALSE, num_dots);
368 memset(ret->face_solved, FALSE, num_faces);
370 ret->dot_yes_count = snewn(num_dots, char);
371 memset(ret->dot_yes_count, 0, num_dots);
372 ret->dot_no_count = snewn(num_dots, char);
373 memset(ret->dot_no_count, 0, num_dots);
374 ret->face_yes_count = snewn(num_faces, char);
375 memset(ret->face_yes_count, 0, num_faces);
376 ret->face_no_count = snewn(num_faces, char);
377 memset(ret->face_no_count, 0, num_faces);
379 if (diff < DIFF_NORMAL) {
382 ret->dlines = snewn(2*num_edges, char);
383 memset(ret->dlines, 0, 2*num_edges);
386 if (diff < DIFF_HARD) {
389 ret->linedsf = snew_dsf(state->game_grid->num_edges);
395 static void free_solver_state(solver_state *sstate) {
397 free_game(sstate->state);
398 sfree(sstate->dotdsf);
399 sfree(sstate->looplen);
400 sfree(sstate->dot_solved);
401 sfree(sstate->face_solved);
402 sfree(sstate->dot_yes_count);
403 sfree(sstate->dot_no_count);
404 sfree(sstate->face_yes_count);
405 sfree(sstate->face_no_count);
407 /* OK, because sfree(NULL) is a no-op */
408 sfree(sstate->dlines);
409 sfree(sstate->linedsf);
415 static solver_state *dup_solver_state(const solver_state *sstate) {
416 game_state *state = sstate->state;
417 int num_dots = state->game_grid->num_dots;
418 int num_faces = state->game_grid->num_faces;
419 int num_edges = state->game_grid->num_edges;
420 solver_state *ret = snew(solver_state);
422 ret->state = state = dup_game(sstate->state);
424 ret->solver_status = sstate->solver_status;
425 ret->diff = sstate->diff;
427 ret->dotdsf = snewn(num_dots, int);
428 ret->looplen = snewn(num_dots, int);
429 memcpy(ret->dotdsf, sstate->dotdsf,
430 num_dots * sizeof(int));
431 memcpy(ret->looplen, sstate->looplen,
432 num_dots * sizeof(int));
434 ret->dot_solved = snewn(num_dots, char);
435 ret->face_solved = snewn(num_faces, char);
436 memcpy(ret->dot_solved, sstate->dot_solved, num_dots);
437 memcpy(ret->face_solved, sstate->face_solved, num_faces);
439 ret->dot_yes_count = snewn(num_dots, char);
440 memcpy(ret->dot_yes_count, sstate->dot_yes_count, num_dots);
441 ret->dot_no_count = snewn(num_dots, char);
442 memcpy(ret->dot_no_count, sstate->dot_no_count, num_dots);
444 ret->face_yes_count = snewn(num_faces, char);
445 memcpy(ret->face_yes_count, sstate->face_yes_count, num_faces);
446 ret->face_no_count = snewn(num_faces, char);
447 memcpy(ret->face_no_count, sstate->face_no_count, num_faces);
449 if (sstate->dlines) {
450 ret->dlines = snewn(2*num_edges, char);
451 memcpy(ret->dlines, sstate->dlines,
457 if (sstate->linedsf) {
458 ret->linedsf = snewn(num_edges, int);
459 memcpy(ret->linedsf, sstate->linedsf,
460 num_edges * sizeof(int));
468 static game_params *default_params(void)
470 game_params *ret = snew(game_params);
479 ret->diff = DIFF_EASY;
485 static game_params *dup_params(const game_params *params)
487 game_params *ret = snew(game_params);
489 *ret = *params; /* structure copy */
493 static const game_params presets[] = {
495 { 7, 7, DIFF_EASY, 0 },
496 { 7, 7, DIFF_NORMAL, 0 },
497 { 7, 7, DIFF_HARD, 0 },
498 { 7, 7, DIFF_HARD, 1 },
499 { 7, 7, DIFF_HARD, 2 },
500 { 5, 5, DIFF_HARD, 3 },
501 { 7, 7, DIFF_HARD, 4 },
502 { 5, 4, DIFF_HARD, 5 },
503 { 5, 5, DIFF_HARD, 6 },
504 { 5, 5, DIFF_HARD, 7 },
505 { 3, 3, DIFF_HARD, 8 },
506 { 3, 3, DIFF_HARD, 9 },
507 { 3, 3, DIFF_HARD, 10 },
508 { 6, 6, DIFF_HARD, 11 },
509 { 6, 6, DIFF_HARD, 12 },
511 { 7, 7, DIFF_EASY, 0 },
512 { 10, 10, DIFF_EASY, 0 },
513 { 7, 7, DIFF_NORMAL, 0 },
514 { 10, 10, DIFF_NORMAL, 0 },
515 { 7, 7, DIFF_HARD, 0 },
516 { 10, 10, DIFF_HARD, 0 },
517 { 10, 10, DIFF_HARD, 1 },
518 { 12, 10, DIFF_HARD, 2 },
519 { 7, 7, DIFF_HARD, 3 },
520 { 9, 9, DIFF_HARD, 4 },
521 { 5, 4, DIFF_HARD, 5 },
522 { 7, 7, DIFF_HARD, 6 },
523 { 5, 5, DIFF_HARD, 7 },
524 { 5, 5, DIFF_HARD, 8 },
525 { 5, 4, DIFF_HARD, 9 },
526 { 5, 4, DIFF_HARD, 10 },
527 { 10, 10, DIFF_HARD, 11 },
528 { 10, 10, DIFF_HARD, 12 }
532 static int game_fetch_preset(int i, char **name, game_params **params)
537 if (i < 0 || i >= lenof(presets))
540 tmppar = snew(game_params);
541 *tmppar = presets[i];
543 sprintf(buf, "%dx%d %s - %s", tmppar->h, tmppar->w,
544 gridnames[tmppar->type], diffnames[tmppar->diff]);
550 static void free_params(game_params *params)
555 static void decode_params(game_params *params, char const *string)
557 params->h = params->w = atoi(string);
558 params->diff = DIFF_EASY;
559 while (*string && isdigit((unsigned char)*string)) string++;
560 if (*string == 'x') {
562 params->h = atoi(string);
563 while (*string && isdigit((unsigned char)*string)) string++;
565 if (*string == 't') {
567 params->type = atoi(string);
568 while (*string && isdigit((unsigned char)*string)) string++;
570 if (*string == 'd') {
573 for (i = 0; i < DIFF_MAX; i++)
574 if (*string == diffchars[i])
576 if (*string) string++;
580 static char *encode_params(const game_params *params, int full)
583 sprintf(str, "%dx%dt%d", params->w, params->h, params->type);
585 sprintf(str + strlen(str), "d%c", diffchars[params->diff]);
589 static config_item *game_configure(const game_params *params)
594 ret = snewn(5, config_item);
596 ret[0].name = "Width";
597 ret[0].type = C_STRING;
598 sprintf(buf, "%d", params->w);
599 ret[0].sval = dupstr(buf);
602 ret[1].name = "Height";
603 ret[1].type = C_STRING;
604 sprintf(buf, "%d", params->h);
605 ret[1].sval = dupstr(buf);
608 ret[2].name = "Grid type";
609 ret[2].type = C_CHOICES;
610 ret[2].sval = GRID_CONFIGS;
611 ret[2].ival = params->type;
613 ret[3].name = "Difficulty";
614 ret[3].type = C_CHOICES;
615 ret[3].sval = DIFFCONFIG;
616 ret[3].ival = params->diff;
626 static game_params *custom_params(const config_item *cfg)
628 game_params *ret = snew(game_params);
630 ret->w = atoi(cfg[0].sval);
631 ret->h = atoi(cfg[1].sval);
632 ret->type = cfg[2].ival;
633 ret->diff = cfg[3].ival;
638 static char *validate_params(const game_params *params, int full)
640 if (params->type < 0 || params->type >= NUM_GRID_TYPES)
641 return "Illegal grid type";
642 if (params->w < grid_size_limits[params->type].amin ||
643 params->h < grid_size_limits[params->type].amin)
644 return grid_size_limits[params->type].aerr;
645 if (params->w < grid_size_limits[params->type].omin &&
646 params->h < grid_size_limits[params->type].omin)
647 return grid_size_limits[params->type].oerr;
650 * This shouldn't be able to happen at all, since decode_params
651 * and custom_params will never generate anything that isn't
654 assert(params->diff < DIFF_MAX);
659 /* Returns a newly allocated string describing the current puzzle */
660 static char *state_to_text(const game_state *state)
662 grid *g = state->game_grid;
664 int num_faces = g->num_faces;
665 char *description = snewn(num_faces + 1, char);
666 char *dp = description;
670 for (i = 0; i < num_faces; i++) {
671 if (state->clues[i] < 0) {
672 if (empty_count > 25) {
673 dp += sprintf(dp, "%c", (int)(empty_count + 'a' - 1));
679 dp += sprintf(dp, "%c", (int)(empty_count + 'a' - 1));
682 dp += sprintf(dp, "%c", (int)CLUE2CHAR(state->clues[i]));
687 dp += sprintf(dp, "%c", (int)(empty_count + 'a' - 1));
689 retval = dupstr(description);
695 #define GRID_DESC_SEP '_'
697 /* Splits up a (optional) grid_desc from the game desc. Returns the
698 * grid_desc (which needs freeing) and updates the desc pointer to
699 * start of real desc, or returns NULL if no desc. */
700 static char *extract_grid_desc(const char **desc)
702 char *sep = strchr(*desc, GRID_DESC_SEP), *gd;
705 if (!sep) return NULL;
707 gd_len = sep - (*desc);
708 gd = snewn(gd_len+1, char);
709 memcpy(gd, *desc, gd_len);
717 /* We require that the params pass the test in validate_params and that the
718 * description fills the entire game area */
719 static char *validate_desc(const game_params *params, const char *desc)
723 char *grid_desc, *ret;
725 /* It's pretty inefficient to do this just for validation. All we need to
726 * know is the precise number of faces. */
727 grid_desc = extract_grid_desc(&desc);
728 ret = grid_validate_desc(grid_types[params->type], params->w, params->h, grid_desc);
731 g = loopy_generate_grid(params, grid_desc);
732 if (grid_desc) sfree(grid_desc);
734 for (; *desc; ++desc) {
735 if ((*desc >= '0' && *desc <= '9') || (*desc >= 'A' && *desc <= 'Z')) {
740 count += *desc - 'a' + 1;
743 return "Unknown character in description";
746 if (count < g->num_faces)
747 return "Description too short for board size";
748 if (count > g->num_faces)
749 return "Description too long for board size";
756 /* Sums the lengths of the numbers in range [0,n) */
757 /* See equivalent function in solo.c for justification of this. */
758 static int len_0_to_n(int n)
760 int len = 1; /* Counting 0 as a bit of a special case */
763 for (i = 1; i < n; i *= 10) {
764 len += max(n - i, 0);
770 static char *encode_solve_move(const game_state *state)
775 int num_edges = state->game_grid->num_edges;
777 /* This is going to return a string representing the moves needed to set
778 * every line in a grid to be the same as the ones in 'state'. The exact
779 * length of this string is predictable. */
781 len = 1; /* Count the 'S' prefix */
782 /* Numbers in all lines */
783 len += len_0_to_n(num_edges);
784 /* For each line we also have a letter */
787 ret = snewn(len + 1, char);
790 p += sprintf(p, "S");
792 for (i = 0; i < num_edges; i++) {
793 switch (state->lines[i]) {
795 p += sprintf(p, "%dy", i);
798 p += sprintf(p, "%dn", i);
803 /* No point in doing sums like that if they're going to be wrong */
804 assert(strlen(ret) <= (size_t)len);
808 static game_ui *new_ui(const game_state *state)
813 static void free_ui(game_ui *ui)
817 static char *encode_ui(const game_ui *ui)
822 static void decode_ui(game_ui *ui, const char *encoding)
826 static void game_changed_state(game_ui *ui, const game_state *oldstate,
827 const game_state *newstate)
831 static void game_compute_size(const game_params *params, int tilesize,
834 int grid_width, grid_height, rendered_width, rendered_height;
837 grid_compute_size(grid_types[params->type], params->w, params->h,
838 &g_tilesize, &grid_width, &grid_height);
840 /* multiply first to minimise rounding error on integer division */
841 rendered_width = grid_width * tilesize / g_tilesize;
842 rendered_height = grid_height * tilesize / g_tilesize;
843 *x = rendered_width + 2 * BORDER(tilesize) + 1;
844 *y = rendered_height + 2 * BORDER(tilesize) + 1;
847 static void game_set_size(drawing *dr, game_drawstate *ds,
848 const game_params *params, int tilesize)
850 ds->tilesize = tilesize;
853 static float *game_colours(frontend *fe, int *ncolours)
855 float *ret = snewn(3 * NCOLOURS, float);
857 frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
859 ret[COL_FOREGROUND * 3 + 0] = 0.0F;
860 ret[COL_FOREGROUND * 3 + 1] = 0.0F;
861 ret[COL_FOREGROUND * 3 + 2] = 0.0F;
864 * We want COL_LINEUNKNOWN to be a yellow which is a bit darker
865 * than the background. (I previously set it to 0.8,0.8,0, but
866 * found that this went badly with the 0.8,0.8,0.8 favoured as a
867 * background by the Java frontend.)
869 ret[COL_LINEUNKNOWN * 3 + 0] = ret[COL_BACKGROUND * 3 + 0] * 0.9F;
870 ret[COL_LINEUNKNOWN * 3 + 1] = ret[COL_BACKGROUND * 3 + 1] * 0.9F;
871 ret[COL_LINEUNKNOWN * 3 + 2] = 0.0F;
873 ret[COL_HIGHLIGHT * 3 + 0] = 1.0F;
874 ret[COL_HIGHLIGHT * 3 + 1] = 1.0F;
875 ret[COL_HIGHLIGHT * 3 + 2] = 1.0F;
877 ret[COL_MISTAKE * 3 + 0] = 1.0F;
878 ret[COL_MISTAKE * 3 + 1] = 0.0F;
879 ret[COL_MISTAKE * 3 + 2] = 0.0F;
881 ret[COL_SATISFIED * 3 + 0] = 0.0F;
882 ret[COL_SATISFIED * 3 + 1] = 0.0F;
883 ret[COL_SATISFIED * 3 + 2] = 0.0F;
885 /* We want the faint lines to be a bit darker than the background.
886 * Except if the background is pretty dark already; then it ought to be a
887 * bit lighter. Oy vey.
889 ret[COL_FAINT * 3 + 0] = ret[COL_BACKGROUND * 3 + 0] * 0.9F;
890 ret[COL_FAINT * 3 + 1] = ret[COL_BACKGROUND * 3 + 1] * 0.9F;
891 ret[COL_FAINT * 3 + 2] = ret[COL_BACKGROUND * 3 + 2] * 0.9F;
893 *ncolours = NCOLOURS;
897 static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
899 struct game_drawstate *ds = snew(struct game_drawstate);
900 int num_faces = state->game_grid->num_faces;
901 int num_edges = state->game_grid->num_edges;
906 ds->lines = snewn(num_edges, char);
907 ds->clue_error = snewn(num_faces, char);
908 ds->clue_satisfied = snewn(num_faces, char);
909 ds->textx = snewn(num_faces, int);
910 ds->texty = snewn(num_faces, int);
913 memset(ds->lines, LINE_UNKNOWN, num_edges);
914 memset(ds->clue_error, 0, num_faces);
915 memset(ds->clue_satisfied, 0, num_faces);
916 for (i = 0; i < num_faces; i++)
917 ds->textx[i] = ds->texty[i] = -1;
922 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
926 sfree(ds->clue_error);
927 sfree(ds->clue_satisfied);
932 static int game_timing_state(const game_state *state, game_ui *ui)
937 static float game_anim_length(const game_state *oldstate,
938 const game_state *newstate, int dir, game_ui *ui)
943 static int game_can_format_as_text_now(const game_params *params)
945 if (params->type != 0)
950 static char *game_text_format(const game_state *state)
956 grid *g = state->game_grid;
959 assert(state->grid_type == 0);
961 /* Work out the basic size unit */
962 f = g->faces; /* first face */
963 assert(f->order == 4);
964 /* The dots are ordered clockwise, so the two opposite
965 * corners are guaranteed to span the square */
966 cell_size = abs(f->dots[0]->x - f->dots[2]->x);
968 w = (g->highest_x - g->lowest_x) / cell_size;
969 h = (g->highest_y - g->lowest_y) / cell_size;
971 /* Create a blank "canvas" to "draw" on */
974 ret = snewn(W * H + 1, char);
975 for (y = 0; y < H; y++) {
976 for (x = 0; x < W-1; x++) {
979 ret[y*W + W-1] = '\n';
983 /* Fill in edge info */
984 for (i = 0; i < g->num_edges; i++) {
985 grid_edge *e = g->edges + i;
986 /* Cell coordinates, from (0,0) to (w-1,h-1) */
987 int x1 = (e->dot1->x - g->lowest_x) / cell_size;
988 int x2 = (e->dot2->x - g->lowest_x) / cell_size;
989 int y1 = (e->dot1->y - g->lowest_y) / cell_size;
990 int y2 = (e->dot2->y - g->lowest_y) / cell_size;
991 /* Midpoint, in canvas coordinates (canvas coordinates are just twice
992 * cell coordinates) */
995 switch (state->lines[i]) {
997 ret[y*W + x] = (y1 == y2) ? '-' : '|';
1003 break; /* already a space */
1005 assert(!"Illegal line state");
1010 for (i = 0; i < g->num_faces; i++) {
1014 assert(f->order == 4);
1015 /* Cell coordinates, from (0,0) to (w-1,h-1) */
1016 x1 = (f->dots[0]->x - g->lowest_x) / cell_size;
1017 x2 = (f->dots[2]->x - g->lowest_x) / cell_size;
1018 y1 = (f->dots[0]->y - g->lowest_y) / cell_size;
1019 y2 = (f->dots[2]->y - g->lowest_y) / cell_size;
1020 /* Midpoint, in canvas coordinates */
1023 ret[y*W + x] = CLUE2CHAR(state->clues[i]);
1028 /* ----------------------------------------------------------------------
1033 static void check_caches(const solver_state* sstate)
1036 const game_state *state = sstate->state;
1037 const grid *g = state->game_grid;
1039 for (i = 0; i < g->num_dots; i++) {
1040 assert(dot_order(state, i, LINE_YES) == sstate->dot_yes_count[i]);
1041 assert(dot_order(state, i, LINE_NO) == sstate->dot_no_count[i]);
1044 for (i = 0; i < g->num_faces; i++) {
1045 assert(face_order(state, i, LINE_YES) == sstate->face_yes_count[i]);
1046 assert(face_order(state, i, LINE_NO) == sstate->face_no_count[i]);
1051 #define check_caches(s) \
1053 fprintf(stderr, "check_caches at line %d\n", __LINE__); \
1057 #endif /* DEBUG_CACHES */
1059 /* ----------------------------------------------------------------------
1060 * Solver utility functions
1063 /* Sets the line (with index i) to the new state 'line_new', and updates
1064 * the cached counts of any affected faces and dots.
1065 * Returns TRUE if this actually changed the line's state. */
1066 static int solver_set_line(solver_state *sstate, int i,
1067 enum line_state line_new
1069 , const char *reason
1073 game_state *state = sstate->state;
1077 assert(line_new != LINE_UNKNOWN);
1079 check_caches(sstate);
1081 if (state->lines[i] == line_new) {
1082 return FALSE; /* nothing changed */
1084 state->lines[i] = line_new;
1087 fprintf(stderr, "solver: set line [%d] to %s (%s)\n",
1088 i, line_new == LINE_YES ? "YES" : "NO",
1092 g = state->game_grid;
1095 /* Update the cache for both dots and both faces affected by this. */
1096 if (line_new == LINE_YES) {
1097 sstate->dot_yes_count[e->dot1 - g->dots]++;
1098 sstate->dot_yes_count[e->dot2 - g->dots]++;
1100 sstate->face_yes_count[e->face1 - g->faces]++;
1103 sstate->face_yes_count[e->face2 - g->faces]++;
1106 sstate->dot_no_count[e->dot1 - g->dots]++;
1107 sstate->dot_no_count[e->dot2 - g->dots]++;
1109 sstate->face_no_count[e->face1 - g->faces]++;
1112 sstate->face_no_count[e->face2 - g->faces]++;
1116 check_caches(sstate);
1121 #define solver_set_line(a, b, c) \
1122 solver_set_line(a, b, c, __FUNCTION__)
1126 * Merge two dots due to the existence of an edge between them.
1127 * Updates the dsf tracking equivalence classes, and keeps track of
1128 * the length of path each dot is currently a part of.
1129 * Returns TRUE if the dots were already linked, ie if they are part of a
1130 * closed loop, and false otherwise.
1132 static int merge_dots(solver_state *sstate, int edge_index)
1135 grid *g = sstate->state->game_grid;
1136 grid_edge *e = g->edges + edge_index;
1138 i = e->dot1 - g->dots;
1139 j = e->dot2 - g->dots;
1141 i = dsf_canonify(sstate->dotdsf, i);
1142 j = dsf_canonify(sstate->dotdsf, j);
1147 len = sstate->looplen[i] + sstate->looplen[j];
1148 dsf_merge(sstate->dotdsf, i, j);
1149 i = dsf_canonify(sstate->dotdsf, i);
1150 sstate->looplen[i] = len;
1155 /* Merge two lines because the solver has deduced that they must be either
1156 * identical or opposite. Returns TRUE if this is new information, otherwise
1158 static int merge_lines(solver_state *sstate, int i, int j, int inverse
1160 , const char *reason
1166 assert(i < sstate->state->game_grid->num_edges);
1167 assert(j < sstate->state->game_grid->num_edges);
1169 i = edsf_canonify(sstate->linedsf, i, &inv_tmp);
1171 j = edsf_canonify(sstate->linedsf, j, &inv_tmp);
1174 edsf_merge(sstate->linedsf, i, j, inverse);
1178 fprintf(stderr, "%s [%d] [%d] %s(%s)\n",
1180 inverse ? "inverse " : "", reason);
1187 #define merge_lines(a, b, c, d) \
1188 merge_lines(a, b, c, d, __FUNCTION__)
1191 /* Count the number of lines of a particular type currently going into the
1193 static int dot_order(const game_state* state, int dot, char line_type)
1196 grid *g = state->game_grid;
1197 grid_dot *d = g->dots + dot;
1200 for (i = 0; i < d->order; i++) {
1201 grid_edge *e = d->edges[i];
1202 if (state->lines[e - g->edges] == line_type)
1208 /* Count the number of lines of a particular type currently surrounding the
1210 static int face_order(const game_state* state, int face, char line_type)
1213 grid *g = state->game_grid;
1214 grid_face *f = g->faces + face;
1217 for (i = 0; i < f->order; i++) {
1218 grid_edge *e = f->edges[i];
1219 if (state->lines[e - g->edges] == line_type)
1225 /* Set all lines bordering a dot of type old_type to type new_type
1226 * Return value tells caller whether this function actually did anything */
1227 static int dot_setall(solver_state *sstate, int dot,
1228 char old_type, char new_type)
1230 int retval = FALSE, r;
1231 game_state *state = sstate->state;
1236 if (old_type == new_type)
1239 g = state->game_grid;
1242 for (i = 0; i < d->order; i++) {
1243 int line_index = d->edges[i] - g->edges;
1244 if (state->lines[line_index] == old_type) {
1245 r = solver_set_line(sstate, line_index, new_type);
1253 /* Set all lines bordering a face of type old_type to type new_type */
1254 static int face_setall(solver_state *sstate, int face,
1255 char old_type, char new_type)
1257 int retval = FALSE, r;
1258 game_state *state = sstate->state;
1263 if (old_type == new_type)
1266 g = state->game_grid;
1267 f = g->faces + face;
1269 for (i = 0; i < f->order; i++) {
1270 int line_index = f->edges[i] - g->edges;
1271 if (state->lines[line_index] == old_type) {
1272 r = solver_set_line(sstate, line_index, new_type);
1280 /* ----------------------------------------------------------------------
1281 * Loop generation and clue removal
1284 static void add_full_clues(game_state *state, random_state *rs)
1286 signed char *clues = state->clues;
1287 grid *g = state->game_grid;
1288 char *board = snewn(g->num_faces, char);
1291 generate_loop(g, board, rs, NULL, NULL);
1293 /* Fill out all the clues by initialising to 0, then iterating over
1294 * all edges and incrementing each clue as we find edges that border
1295 * between BLACK/WHITE faces. While we're at it, we verify that the
1296 * algorithm does work, and there aren't any GREY faces still there. */
1297 memset(clues, 0, g->num_faces);
1298 for (i = 0; i < g->num_edges; i++) {
1299 grid_edge *e = g->edges + i;
1300 grid_face *f1 = e->face1;
1301 grid_face *f2 = e->face2;
1302 enum face_colour c1 = FACE_COLOUR(f1);
1303 enum face_colour c2 = FACE_COLOUR(f2);
1304 assert(c1 != FACE_GREY);
1305 assert(c2 != FACE_GREY);
1307 if (f1) clues[f1 - g->faces]++;
1308 if (f2) clues[f2 - g->faces]++;
1315 static int game_has_unique_soln(const game_state *state, int diff)
1318 solver_state *sstate_new;
1319 solver_state *sstate = new_solver_state((game_state *)state, diff);
1321 sstate_new = solve_game_rec(sstate);
1323 assert(sstate_new->solver_status != SOLVER_MISTAKE);
1324 ret = (sstate_new->solver_status == SOLVER_SOLVED);
1326 free_solver_state(sstate_new);
1327 free_solver_state(sstate);
1333 /* Remove clues one at a time at random. */
1334 static game_state *remove_clues(game_state *state, random_state *rs,
1338 int num_faces = state->game_grid->num_faces;
1339 game_state *ret = dup_game(state), *saved_ret;
1342 /* We need to remove some clues. We'll do this by forming a list of all
1343 * available clues, shuffling it, then going along one at a
1344 * time clearing each clue in turn for which doing so doesn't render the
1345 * board unsolvable. */
1346 face_list = snewn(num_faces, int);
1347 for (n = 0; n < num_faces; ++n) {
1351 shuffle(face_list, num_faces, sizeof(int), rs);
1353 for (n = 0; n < num_faces; ++n) {
1354 saved_ret = dup_game(ret);
1355 ret->clues[face_list[n]] = -1;
1357 if (game_has_unique_soln(ret, diff)) {
1358 free_game(saved_ret);
1370 static char *new_game_desc(const game_params *params, random_state *rs,
1371 char **aux, int interactive)
1373 /* solution and description both use run-length encoding in obvious ways */
1374 char *retval, *game_desc, *grid_desc;
1376 game_state *state = snew(game_state);
1377 game_state *state_new;
1379 grid_desc = grid_new_desc(grid_types[params->type], params->w, params->h, rs);
1380 state->game_grid = g = loopy_generate_grid(params, grid_desc);
1382 state->clues = snewn(g->num_faces, signed char);
1383 state->lines = snewn(g->num_edges, char);
1384 state->line_errors = snewn(g->num_edges, unsigned char);
1385 state->exactly_one_loop = FALSE;
1387 state->grid_type = params->type;
1391 memset(state->lines, LINE_UNKNOWN, g->num_edges);
1392 memset(state->line_errors, 0, g->num_edges);
1394 state->solved = state->cheated = FALSE;
1396 /* Get a new random solvable board with all its clues filled in. Yes, this
1397 * can loop for ever if the params are suitably unfavourable, but
1398 * preventing games smaller than 4x4 seems to stop this happening */
1400 add_full_clues(state, rs);
1401 } while (!game_has_unique_soln(state, params->diff));
1403 state_new = remove_clues(state, rs, params->diff);
1408 if (params->diff > 0 && game_has_unique_soln(state, params->diff-1)) {
1410 fprintf(stderr, "Rejecting board, it is too easy\n");
1412 goto newboard_please;
1415 game_desc = state_to_text(state);
1420 retval = snewn(strlen(grid_desc) + 1 + strlen(game_desc) + 1, char);
1421 sprintf(retval, "%s%c%s", grid_desc, (int)GRID_DESC_SEP, game_desc);
1428 assert(!validate_desc(params, retval));
1433 static game_state *new_game(midend *me, const game_params *params,
1437 game_state *state = snew(game_state);
1438 int empties_to_make = 0;
1443 int num_faces, num_edges;
1445 grid_desc = extract_grid_desc(&desc);
1446 state->game_grid = g = loopy_generate_grid(params, grid_desc);
1447 if (grid_desc) sfree(grid_desc);
1451 num_faces = g->num_faces;
1452 num_edges = g->num_edges;
1454 state->clues = snewn(num_faces, signed char);
1455 state->lines = snewn(num_edges, char);
1456 state->line_errors = snewn(num_edges, unsigned char);
1457 state->exactly_one_loop = FALSE;
1459 state->solved = state->cheated = FALSE;
1461 state->grid_type = params->type;
1463 for (i = 0; i < num_faces; i++) {
1464 if (empties_to_make) {
1466 state->clues[i] = -1;
1472 n2 = *dp - 'A' + 10;
1473 if (n >= 0 && n < 10) {
1474 state->clues[i] = n;
1475 } else if (n2 >= 10 && n2 < 36) {
1476 state->clues[i] = n2;
1480 state->clues[i] = -1;
1481 empties_to_make = n - 1;
1486 memset(state->lines, LINE_UNKNOWN, num_edges);
1487 memset(state->line_errors, 0, num_edges);
1491 /* Calculates the line_errors data, and checks if the current state is a
1493 static int check_completion(game_state *state)
1495 grid *g = state->game_grid;
1497 int *dsf, *component_state;
1498 int nsilly, nloop, npath, largest_comp, largest_size;
1499 enum { COMP_NONE, COMP_LOOP, COMP_PATH, COMP_SILLY, COMP_EMPTY };
1501 memset(state->line_errors, 0, g->num_edges);
1504 * Find loops in the grid, and determine whether the puzzle is
1507 * Loopy is a bit more complicated than most puzzles that care
1508 * about loop detection. In most of them, loops are simply
1509 * _forbidden_; so the obviously right way to do
1510 * error-highlighting during play is to light up a graph edge red
1511 * iff it is part of a loop, which is exactly what the centralised
1512 * findloop.c makes easy.
1514 * But Loopy is unusual in that you're _supposed_ to be making a
1515 * loop - and yet _some_ loops are not the right loop. So we need
1516 * to be more discriminating, by identifying loops one by one and
1517 * then thinking about which ones to highlight, and so findloop.c
1518 * isn't quite the right tool for the job in this case.
1520 * Worse still, consider situations in which the grid contains a
1521 * loop and also some non-loop edges: there are some cases like
1522 * this in which the user's intuitive expectation would be to
1523 * highlight the loop (if you're only about half way through the
1524 * puzzle and have accidentally made a little loop in some corner
1525 * of the grid), and others in which they'd be more likely to
1526 * expect you to highlight the non-loop edges (if you've just
1527 * closed off a whole loop that you thought was the entire
1528 * solution, but forgot some disconnected edges in a corner
1529 * somewhere). So while it's easy enough to check whether the
1530 * solution is _right_, highlighting the wrong parts is a tricky
1531 * problem for this puzzle!
1533 * I'd quite like, in some situations, to identify the largest
1534 * loop among the player's YES edges, and then light up everything
1535 * other than that. But finding the longest cycle in a graph is an
1536 * NP-complete problem (because, in particular, it must return a
1537 * Hamilton cycle if one exists).
1539 * However, I think we can make the problem tractable by
1540 * exercising the Puzzles principle that it isn't absolutely
1541 * necessary to highlight _all_ errors: the key point is that by
1542 * the time the user has filled in the whole grid, they should
1543 * either have seen a completion flash, or have _some_ error
1544 * highlight showing them why the solution isn't right. So in
1545 * principle it would be *just about* good enough to highlight
1546 * just one error in the whole grid, if there was really no better
1547 * way. But we'd like to highlight as many errors as possible.
1549 * In this case, I think the simple approach is to make use of the
1550 * fact that no vertex may have degree > 2, and that's really
1551 * simple to detect. So the plan goes like this:
1553 * - Form the dsf of connected components of the graph vertices.
1555 * - Highlight an error at any vertex with degree > 2. (It so
1556 * happens that we do this by lighting up all the edges
1557 * incident to that vertex, but that's an output detail.)
1559 * - Any component that contains such a vertex is now excluded
1560 * from further consideration, because it already has a
1563 * - The remaining components have no vertex with degree > 2, and
1564 * hence they all consist of either a simple loop, or a simple
1565 * path with two endpoints.
1567 * - If the sensible components are all paths, or if there's
1568 * exactly one of them and it is a loop, then highlight no
1569 * further edge errors. (The former case is normal during play,
1570 * and the latter is a potentially solved puzzle.)
1572 * - Otherwise - if there is more than one sensible component
1573 * _and_ at least one of them is a loop - find the largest of
1574 * the sensible components, leave that one unhighlighted, and
1575 * light the rest up in red.
1578 dsf = snew_dsf(g->num_dots);
1580 /* Build the dsf. */
1581 for (i = 0; i < g->num_edges; i++) {
1582 if (state->lines[i] == LINE_YES) {
1583 grid_edge *e = g->edges + i;
1584 int d1 = e->dot1 - g->dots, d2 = e->dot2 - g->dots;
1585 dsf_merge(dsf, d1, d2);
1589 /* Initialise a state variable for each connected component. */
1590 component_state = snewn(g->num_dots, int);
1591 for (i = 0; i < g->num_dots; i++) {
1592 if (dsf_canonify(dsf, i) == i)
1593 component_state[i] = COMP_LOOP;
1595 component_state[i] = COMP_NONE;
1598 /* Check for dots with degree > 3. Here we also spot dots of
1599 * degree 1 in which the user has marked all the non-edges as
1600 * LINE_NO, because those are also clear vertex-level errors, so
1601 * we give them the same treatment of excluding their connected
1602 * component from the subsequent loop analysis. */
1603 for (i = 0; i < g->num_dots; i++) {
1604 int comp = dsf_canonify(dsf, i);
1605 int yes = dot_order(state, i, LINE_YES);
1606 int unknown = dot_order(state, i, LINE_UNKNOWN);
1607 if ((yes == 1 && unknown == 0) || (yes >= 3)) {
1608 /* violation, so mark all YES edges as errors */
1609 grid_dot *d = g->dots + i;
1611 for (j = 0; j < d->order; j++) {
1612 int e = d->edges[j] - g->edges;
1613 if (state->lines[e] == LINE_YES)
1614 state->line_errors[e] = TRUE;
1616 /* And mark this component as not worthy of further
1618 component_state[comp] = COMP_SILLY;
1620 } else if (yes == 0) {
1621 /* A completely isolated dot must also be excluded it from
1622 * the subsequent loop highlighting pass, but we tag it
1623 * with a different enum value to avoid it counting
1624 * towards the components that inhibit returning a win
1626 component_state[comp] = COMP_EMPTY;
1627 } else if (yes == 1) {
1628 /* A dot with degree 1 that didn't fall into the 'clearly
1629 * erroneous' case above indicates that this connected
1630 * component will be a path rather than a loop - unless
1631 * something worse elsewhere in the component has
1632 * classified it as silly. */
1633 if (component_state[comp] != COMP_SILLY)
1634 component_state[comp] = COMP_PATH;
1638 /* Count up the components. Also, find the largest sensible
1639 * component. (Tie-breaking condition is derived from the order of
1640 * vertices in the grid data structure, which is fairly arbitrary
1641 * but at least stays stable throughout the game.) */
1642 nsilly = nloop = npath = 0;
1643 largest_comp = largest_size = -1;
1644 for (i = 0; i < g->num_dots; i++) {
1645 if (component_state[i] == COMP_SILLY) {
1647 } else if (component_state[i] == COMP_PATH ||
1648 component_state[i] == COMP_LOOP) {
1651 if (component_state[i] == COMP_PATH)
1653 else if (component_state[i] == COMP_LOOP)
1656 if ((this_size = dsf_size(dsf, i)) > largest_size) {
1658 largest_size = this_size;
1663 if (nloop > 0 && nloop + npath > 1) {
1665 * If there are at least two sensible components including at
1666 * least one loop, highlight all edges in every sensible
1667 * component that is not the largest one.
1669 for (i = 0; i < g->num_edges; i++) {
1670 if (state->lines[i] == LINE_YES) {
1671 grid_edge *e = g->edges + i;
1672 int d1 = e->dot1 - g->dots; /* either endpoint is good enough */
1673 int comp = dsf_canonify(dsf, d1);
1674 if (component_state[comp] != COMP_SILLY &&
1675 comp != largest_comp)
1676 state->line_errors[i] = TRUE;
1681 if (nloop == 1 && npath == 0 && nsilly == 0) {
1683 * If there is exactly one component and it is a loop, then
1684 * the puzzle is potentially complete, so check the clues.
1688 for (i = 0; i < g->num_faces; i++) {
1689 int c = state->clues[i];
1690 if (c >= 0 && face_order(state, i, LINE_YES) != c) {
1697 * Also, whether or not the puzzle is actually complete, set
1698 * the flag that says this game_state has exactly one loop and
1699 * nothing else, which will be used to vary the semantics of
1700 * clue highlighting at display time.
1702 state->exactly_one_loop = TRUE;
1705 state->exactly_one_loop = FALSE;
1708 sfree(component_state);
1714 /* ----------------------------------------------------------------------
1717 * Our solver modes operate as follows. Each mode also uses the modes above it.
1720 * Just implement the rules of the game.
1722 * Normal and Tricky Modes
1723 * For each (adjacent) pair of lines through each dot we store a bit for
1724 * whether at least one of them is on and whether at most one is on. (If we
1725 * know both or neither is on that's already stored more directly.)
1728 * Use edsf data structure to make equivalence classes of lines that are
1729 * known identical to or opposite to one another.
1734 * For general grids, we consider "dlines" to be pairs of lines joined
1735 * at a dot. The lines must be adjacent around the dot, so we can think of
1736 * a dline as being a dot+face combination. Or, a dot+edge combination where
1737 * the second edge is taken to be the next clockwise edge from the dot.
1738 * Original loopy code didn't have this extra restriction of the lines being
1739 * adjacent. From my tests with square grids, this extra restriction seems to
1740 * take little, if anything, away from the quality of the puzzles.
1741 * A dline can be uniquely identified by an edge/dot combination, given that
1742 * a dline-pair always goes clockwise around its common dot. The edge/dot
1743 * combination can be represented by an edge/bool combination - if bool is
1744 * TRUE, use edge->dot1 else use edge->dot2. So the total number of dlines is
1745 * exactly twice the number of edges in the grid - although the dlines
1746 * spanning the infinite face are not all that useful to the solver.
1747 * Note that, by convention, a dline goes clockwise around its common dot,
1748 * which means the dline goes anti-clockwise around its common face.
1751 /* Helper functions for obtaining an index into an array of dlines, given
1752 * various information. We assume the grid layout conventions about how
1753 * the various lists are interleaved - see grid_make_consistent() for
1756 /* i points to the first edge of the dline pair, reading clockwise around
1758 static int dline_index_from_dot(grid *g, grid_dot *d, int i)
1760 grid_edge *e = d->edges[i];
1765 if (i2 == d->order) i2 = 0;
1768 ret = 2 * (e - g->edges) + ((e->dot1 == d) ? 1 : 0);
1770 printf("dline_index_from_dot: d=%d,i=%d, edges [%d,%d] - %d\n",
1771 (int)(d - g->dots), i, (int)(e - g->edges),
1772 (int)(e2 - g->edges), ret);
1776 /* i points to the second edge of the dline pair, reading clockwise around
1777 * the face. That is, the edges of the dline, starting at edge{i}, read
1778 * anti-clockwise around the face. By layout conventions, the common dot
1779 * of the dline will be f->dots[i] */
1780 static int dline_index_from_face(grid *g, grid_face *f, int i)
1782 grid_edge *e = f->edges[i];
1783 grid_dot *d = f->dots[i];
1788 if (i2 < 0) i2 += f->order;
1791 ret = 2 * (e - g->edges) + ((e->dot1 == d) ? 1 : 0);
1793 printf("dline_index_from_face: f=%d,i=%d, edges [%d,%d] - %d\n",
1794 (int)(f - g->faces), i, (int)(e - g->edges),
1795 (int)(e2 - g->edges), ret);
1799 static int is_atleastone(const char *dline_array, int index)
1801 return BIT_SET(dline_array[index], 0);
1803 static int set_atleastone(char *dline_array, int index)
1805 return SET_BIT(dline_array[index], 0);
1807 static int is_atmostone(const char *dline_array, int index)
1809 return BIT_SET(dline_array[index], 1);
1811 static int set_atmostone(char *dline_array, int index)
1813 return SET_BIT(dline_array[index], 1);
1816 static void array_setall(char *array, char from, char to, int len)
1818 char *p = array, *p_old = p;
1819 int len_remaining = len;
1821 while ((p = memchr(p, from, len_remaining))) {
1823 len_remaining -= p - p_old;
1828 /* Helper, called when doing dline dot deductions, in the case where we
1829 * have 4 UNKNOWNs, and two of them (adjacent) have *exactly* one YES between
1830 * them (because of dline atmostone/atleastone).
1831 * On entry, edge points to the first of these two UNKNOWNs. This function
1832 * will find the opposite UNKNOWNS (if they are adjacent to one another)
1833 * and set their corresponding dline to atleastone. (Setting atmostone
1834 * already happens in earlier dline deductions) */
1835 static int dline_set_opp_atleastone(solver_state *sstate,
1836 grid_dot *d, int edge)
1838 game_state *state = sstate->state;
1839 grid *g = state->game_grid;
1842 for (opp = 0; opp < N; opp++) {
1843 int opp_dline_index;
1844 if (opp == edge || opp == edge+1 || opp == edge-1)
1846 if (opp == 0 && edge == N-1)
1848 if (opp == N-1 && edge == 0)
1851 if (opp2 == N) opp2 = 0;
1852 /* Check if opp, opp2 point to LINE_UNKNOWNs */
1853 if (state->lines[d->edges[opp] - g->edges] != LINE_UNKNOWN)
1855 if (state->lines[d->edges[opp2] - g->edges] != LINE_UNKNOWN)
1857 /* Found opposite UNKNOWNS and they're next to each other */
1858 opp_dline_index = dline_index_from_dot(g, d, opp);
1859 return set_atleastone(sstate->dlines, opp_dline_index);
1865 /* Set pairs of lines around this face which are known to be identical, to
1866 * the given line_state */
1867 static int face_setall_identical(solver_state *sstate, int face_index,
1868 enum line_state line_new)
1870 /* can[dir] contains the canonical line associated with the line in
1871 * direction dir from the square in question. Similarly inv[dir] is
1872 * whether or not the line in question is inverse to its canonical
1875 game_state *state = sstate->state;
1876 grid *g = state->game_grid;
1877 grid_face *f = g->faces + face_index;
1880 int can1, can2, inv1, inv2;
1882 for (i = 0; i < N; i++) {
1883 int line1_index = f->edges[i] - g->edges;
1884 if (state->lines[line1_index] != LINE_UNKNOWN)
1886 for (j = i + 1; j < N; j++) {
1887 int line2_index = f->edges[j] - g->edges;
1888 if (state->lines[line2_index] != LINE_UNKNOWN)
1891 /* Found two UNKNOWNS */
1892 can1 = edsf_canonify(sstate->linedsf, line1_index, &inv1);
1893 can2 = edsf_canonify(sstate->linedsf, line2_index, &inv2);
1894 if (can1 == can2 && inv1 == inv2) {
1895 solver_set_line(sstate, line1_index, line_new);
1896 solver_set_line(sstate, line2_index, line_new);
1903 /* Given a dot or face, and a count of LINE_UNKNOWNs, find them and
1904 * return the edge indices into e. */
1905 static void find_unknowns(game_state *state,
1906 grid_edge **edge_list, /* Edge list to search (from a face or a dot) */
1907 int expected_count, /* Number of UNKNOWNs (comes from solver's cache) */
1908 int *e /* Returned edge indices */)
1911 grid *g = state->game_grid;
1912 while (c < expected_count) {
1913 int line_index = *edge_list - g->edges;
1914 if (state->lines[line_index] == LINE_UNKNOWN) {
1922 /* If we have a list of edges, and we know whether the number of YESs should
1923 * be odd or even, and there are only a few UNKNOWNs, we can do some simple
1924 * linedsf deductions. This can be used for both face and dot deductions.
1925 * Returns the difficulty level of the next solver that should be used,
1926 * or DIFF_MAX if no progress was made. */
1927 static int parity_deductions(solver_state *sstate,
1928 grid_edge **edge_list, /* Edge list (from a face or a dot) */
1929 int total_parity, /* Expected number of YESs modulo 2 (either 0 or 1) */
1932 game_state *state = sstate->state;
1933 int diff = DIFF_MAX;
1934 int *linedsf = sstate->linedsf;
1936 if (unknown_count == 2) {
1937 /* Lines are known alike/opposite, depending on inv. */
1939 find_unknowns(state, edge_list, 2, e);
1940 if (merge_lines(sstate, e[0], e[1], total_parity))
1941 diff = min(diff, DIFF_HARD);
1942 } else if (unknown_count == 3) {
1944 int can[3]; /* canonical edges */
1945 int inv[3]; /* whether can[x] is inverse to e[x] */
1946 find_unknowns(state, edge_list, 3, e);
1947 can[0] = edsf_canonify(linedsf, e[0], inv);
1948 can[1] = edsf_canonify(linedsf, e[1], inv+1);
1949 can[2] = edsf_canonify(linedsf, e[2], inv+2);
1950 if (can[0] == can[1]) {
1951 if (solver_set_line(sstate, e[2], (total_parity^inv[0]^inv[1]) ?
1952 LINE_YES : LINE_NO))
1953 diff = min(diff, DIFF_EASY);
1955 if (can[0] == can[2]) {
1956 if (solver_set_line(sstate, e[1], (total_parity^inv[0]^inv[2]) ?
1957 LINE_YES : LINE_NO))
1958 diff = min(diff, DIFF_EASY);
1960 if (can[1] == can[2]) {
1961 if (solver_set_line(sstate, e[0], (total_parity^inv[1]^inv[2]) ?
1962 LINE_YES : LINE_NO))
1963 diff = min(diff, DIFF_EASY);
1965 } else if (unknown_count == 4) {
1967 int can[4]; /* canonical edges */
1968 int inv[4]; /* whether can[x] is inverse to e[x] */
1969 find_unknowns(state, edge_list, 4, e);
1970 can[0] = edsf_canonify(linedsf, e[0], inv);
1971 can[1] = edsf_canonify(linedsf, e[1], inv+1);
1972 can[2] = edsf_canonify(linedsf, e[2], inv+2);
1973 can[3] = edsf_canonify(linedsf, e[3], inv+3);
1974 if (can[0] == can[1]) {
1975 if (merge_lines(sstate, e[2], e[3], total_parity^inv[0]^inv[1]))
1976 diff = min(diff, DIFF_HARD);
1977 } else if (can[0] == can[2]) {
1978 if (merge_lines(sstate, e[1], e[3], total_parity^inv[0]^inv[2]))
1979 diff = min(diff, DIFF_HARD);
1980 } else if (can[0] == can[3]) {
1981 if (merge_lines(sstate, e[1], e[2], total_parity^inv[0]^inv[3]))
1982 diff = min(diff, DIFF_HARD);
1983 } else if (can[1] == can[2]) {
1984 if (merge_lines(sstate, e[0], e[3], total_parity^inv[1]^inv[2]))
1985 diff = min(diff, DIFF_HARD);
1986 } else if (can[1] == can[3]) {
1987 if (merge_lines(sstate, e[0], e[2], total_parity^inv[1]^inv[3]))
1988 diff = min(diff, DIFF_HARD);
1989 } else if (can[2] == can[3]) {
1990 if (merge_lines(sstate, e[0], e[1], total_parity^inv[2]^inv[3]))
1991 diff = min(diff, DIFF_HARD);
1999 * These are the main solver functions.
2001 * Their return values are diff values corresponding to the lowest mode solver
2002 * that would notice the work that they have done. For example if the normal
2003 * mode solver adds actual lines or crosses, it will return DIFF_EASY as the
2004 * easy mode solver might be able to make progress using that. It doesn't make
2005 * sense for one of them to return a diff value higher than that of the
2008 * Each function returns the lowest value it can, as early as possible, in
2009 * order to try and pass as much work as possible back to the lower level
2010 * solvers which progress more quickly.
2013 /* PROPOSED NEW DESIGN:
2014 * We have a work queue consisting of 'events' notifying us that something has
2015 * happened that a particular solver mode might be interested in. For example
2016 * the hard mode solver might do something that helps the normal mode solver at
2017 * dot [x,y] in which case it will enqueue an event recording this fact. Then
2018 * we pull events off the work queue, and hand each in turn to the solver that
2019 * is interested in them. If a solver reports that it failed we pass the same
2020 * event on to progressively more advanced solvers and the loop detector. Once
2021 * we've exhausted an event, or it has helped us progress, we drop it and
2022 * continue to the next one. The events are sorted first in order of solver
2023 * complexity (easy first) then order of insertion (oldest first).
2024 * Once we run out of events we loop over each permitted solver in turn
2025 * (easiest first) until either a deduction is made (and an event therefore
2026 * emerges) or no further deductions can be made (in which case we've failed).
2029 * * How do we 'loop over' a solver when both dots and squares are concerned.
2030 * Answer: first all squares then all dots.
2033 static int trivial_deductions(solver_state *sstate)
2035 int i, current_yes, current_no;
2036 game_state *state = sstate->state;
2037 grid *g = state->game_grid;
2038 int diff = DIFF_MAX;
2040 /* Per-face deductions */
2041 for (i = 0; i < g->num_faces; i++) {
2042 grid_face *f = g->faces + i;
2044 if (sstate->face_solved[i])
2047 current_yes = sstate->face_yes_count[i];
2048 current_no = sstate->face_no_count[i];
2050 if (current_yes + current_no == f->order) {
2051 sstate->face_solved[i] = TRUE;
2055 if (state->clues[i] < 0)
2059 * This code checks whether the numeric clue on a face is so
2060 * large as to permit all its remaining LINE_UNKNOWNs to be
2061 * filled in as LINE_YES, or alternatively so small as to
2062 * permit them all to be filled in as LINE_NO.
2065 if (state->clues[i] < current_yes) {
2066 sstate->solver_status = SOLVER_MISTAKE;
2069 if (state->clues[i] == current_yes) {
2070 if (face_setall(sstate, i, LINE_UNKNOWN, LINE_NO))
2071 diff = min(diff, DIFF_EASY);
2072 sstate->face_solved[i] = TRUE;
2076 if (f->order - state->clues[i] < current_no) {
2077 sstate->solver_status = SOLVER_MISTAKE;
2080 if (f->order - state->clues[i] == current_no) {
2081 if (face_setall(sstate, i, LINE_UNKNOWN, LINE_YES))
2082 diff = min(diff, DIFF_EASY);
2083 sstate->face_solved[i] = TRUE;
2087 if (f->order - state->clues[i] == current_no + 1 &&
2088 f->order - current_yes - current_no > 2) {
2090 * One small refinement to the above: we also look for any
2091 * adjacent pair of LINE_UNKNOWNs around the face with
2092 * some LINE_YES incident on it from elsewhere. If we find
2093 * one, then we know that pair of LINE_UNKNOWNs can't
2094 * _both_ be LINE_YES, and hence that pushes us one line
2095 * closer to being able to determine all the rest.
2097 int j, k, e1, e2, e, d;
2099 for (j = 0; j < f->order; j++) {
2100 e1 = f->edges[j] - g->edges;
2101 e2 = f->edges[j+1 < f->order ? j+1 : 0] - g->edges;
2103 if (g->edges[e1].dot1 == g->edges[e2].dot1 ||
2104 g->edges[e1].dot1 == g->edges[e2].dot2) {
2105 d = g->edges[e1].dot1 - g->dots;
2107 assert(g->edges[e1].dot2 == g->edges[e2].dot1 ||
2108 g->edges[e1].dot2 == g->edges[e2].dot2);
2109 d = g->edges[e1].dot2 - g->dots;
2112 if (state->lines[e1] == LINE_UNKNOWN &&
2113 state->lines[e2] == LINE_UNKNOWN) {
2114 for (k = 0; k < g->dots[d].order; k++) {
2115 int e = g->dots[d].edges[k] - g->edges;
2116 if (state->lines[e] == LINE_YES)
2117 goto found; /* multi-level break */
2125 * If we get here, we've found such a pair of edges, and
2126 * they're e1 and e2.
2128 for (j = 0; j < f->order; j++) {
2129 e = f->edges[j] - g->edges;
2130 if (state->lines[e] == LINE_UNKNOWN && e != e1 && e != e2) {
2131 int r = solver_set_line(sstate, e, LINE_YES);
2133 diff = min(diff, DIFF_EASY);
2139 check_caches(sstate);
2141 /* Per-dot deductions */
2142 for (i = 0; i < g->num_dots; i++) {
2143 grid_dot *d = g->dots + i;
2144 int yes, no, unknown;
2146 if (sstate->dot_solved[i])
2149 yes = sstate->dot_yes_count[i];
2150 no = sstate->dot_no_count[i];
2151 unknown = d->order - yes - no;
2155 sstate->dot_solved[i] = TRUE;
2156 } else if (unknown == 1) {
2157 dot_setall(sstate, i, LINE_UNKNOWN, LINE_NO);
2158 diff = min(diff, DIFF_EASY);
2159 sstate->dot_solved[i] = TRUE;
2161 } else if (yes == 1) {
2163 sstate->solver_status = SOLVER_MISTAKE;
2165 } else if (unknown == 1) {
2166 dot_setall(sstate, i, LINE_UNKNOWN, LINE_YES);
2167 diff = min(diff, DIFF_EASY);
2169 } else if (yes == 2) {
2171 dot_setall(sstate, i, LINE_UNKNOWN, LINE_NO);
2172 diff = min(diff, DIFF_EASY);
2174 sstate->dot_solved[i] = TRUE;
2176 sstate->solver_status = SOLVER_MISTAKE;
2181 check_caches(sstate);
2186 static int dline_deductions(solver_state *sstate)
2188 game_state *state = sstate->state;
2189 grid *g = state->game_grid;
2190 char *dlines = sstate->dlines;
2192 int diff = DIFF_MAX;
2194 /* ------ Face deductions ------ */
2196 /* Given a set of dline atmostone/atleastone constraints, need to figure
2197 * out if we can deduce any further info. For more general faces than
2198 * squares, this turns out to be a tricky problem.
2199 * The approach taken here is to define (per face) NxN matrices:
2200 * "maxs" and "mins".
2201 * The entries maxs(j,k) and mins(j,k) define the upper and lower limits
2202 * for the possible number of edges that are YES between positions j and k
2203 * going clockwise around the face. Can think of j and k as marking dots
2204 * around the face (recall the labelling scheme: edge0 joins dot0 to dot1,
2205 * edge1 joins dot1 to dot2 etc).
2206 * Trivially, mins(j,j) = maxs(j,j) = 0, and we don't even bother storing
2207 * these. mins(j,j+1) and maxs(j,j+1) are determined by whether edge{j}
2208 * is YES, NO or UNKNOWN. mins(j,j+2) and maxs(j,j+2) are related to
2209 * the dline atmostone/atleastone status for edges j and j+1.
2211 * Then we calculate the remaining entries recursively. We definitely
2213 * mins(j,k) >= { mins(j,u) + mins(u,k) } for any u between j and k.
2214 * This is because any valid placement of YESs between j and k must give
2215 * a valid placement between j and u, and also between u and k.
2216 * I believe it's sufficient to use just the two values of u:
2217 * j+1 and j+2. Seems to work well in practice - the bounds we compute
2218 * are rigorous, even if they might not be best-possible.
2220 * Once we have maxs and mins calculated, we can make inferences about
2221 * each dline{j,j+1} by looking at the possible complementary edge-counts
2222 * mins(j+2,j) and maxs(j+2,j) and comparing these with the face clue.
2223 * As well as dlines, we can make similar inferences about single edges.
2224 * For example, consider a pentagon with clue 3, and we know at most one
2225 * of (edge0, edge1) is YES, and at most one of (edge2, edge3) is YES.
2226 * We could then deduce edge4 is YES, because maxs(0,4) would be 2, so
2227 * that final edge would have to be YES to make the count up to 3.
2230 /* Much quicker to allocate arrays on the stack than the heap, so
2231 * define the largest possible face size, and base our array allocations
2232 * on that. We check this with an assertion, in case someone decides to
2233 * make a grid which has larger faces than this. Note, this algorithm
2234 * could get quite expensive if there are many large faces. */
2235 #define MAX_FACE_SIZE 12
2237 for (i = 0; i < g->num_faces; i++) {
2238 int maxs[MAX_FACE_SIZE][MAX_FACE_SIZE];
2239 int mins[MAX_FACE_SIZE][MAX_FACE_SIZE];
2240 grid_face *f = g->faces + i;
2243 int clue = state->clues[i];
2244 assert(N <= MAX_FACE_SIZE);
2245 if (sstate->face_solved[i])
2247 if (clue < 0) continue;
2249 /* Calculate the (j,j+1) entries */
2250 for (j = 0; j < N; j++) {
2251 int edge_index = f->edges[j] - g->edges;
2253 enum line_state line1 = state->lines[edge_index];
2254 enum line_state line2;
2258 maxs[j][k] = (line1 == LINE_NO) ? 0 : 1;
2259 mins[j][k] = (line1 == LINE_YES) ? 1 : 0;
2260 /* Calculate the (j,j+2) entries */
2261 dline_index = dline_index_from_face(g, f, k);
2262 edge_index = f->edges[k] - g->edges;
2263 line2 = state->lines[edge_index];
2269 if (line1 == LINE_NO) tmp--;
2270 if (line2 == LINE_NO) tmp--;
2271 if (tmp == 2 && is_atmostone(dlines, dline_index))
2277 if (line1 == LINE_YES) tmp++;
2278 if (line2 == LINE_YES) tmp++;
2279 if (tmp == 0 && is_atleastone(dlines, dline_index))
2284 /* Calculate the (j,j+m) entries for m between 3 and N-1 */
2285 for (m = 3; m < N; m++) {
2286 for (j = 0; j < N; j++) {
2294 maxs[j][k] = maxs[j][u] + maxs[u][k];
2295 mins[j][k] = mins[j][u] + mins[u][k];
2296 tmp = maxs[j][v] + maxs[v][k];
2297 maxs[j][k] = min(maxs[j][k], tmp);
2298 tmp = mins[j][v] + mins[v][k];
2299 mins[j][k] = max(mins[j][k], tmp);
2303 /* See if we can make any deductions */
2304 for (j = 0; j < N; j++) {
2306 grid_edge *e = f->edges[j];
2307 int line_index = e - g->edges;
2310 if (state->lines[line_index] != LINE_UNKNOWN)
2315 /* minimum YESs in the complement of this edge */
2316 if (mins[k][j] > clue) {
2317 sstate->solver_status = SOLVER_MISTAKE;
2320 if (mins[k][j] == clue) {
2321 /* setting this edge to YES would make at least
2322 * (clue+1) edges - contradiction */
2323 solver_set_line(sstate, line_index, LINE_NO);
2324 diff = min(diff, DIFF_EASY);
2326 if (maxs[k][j] < clue - 1) {
2327 sstate->solver_status = SOLVER_MISTAKE;
2330 if (maxs[k][j] == clue - 1) {
2331 /* Only way to satisfy the clue is to set edge{j} as YES */
2332 solver_set_line(sstate, line_index, LINE_YES);
2333 diff = min(diff, DIFF_EASY);
2336 /* More advanced deduction that allows propagation along diagonal
2337 * chains of faces connected by dots, for example, 3-2-...-2-3
2338 * in square grids. */
2339 if (sstate->diff >= DIFF_TRICKY) {
2340 /* Now see if we can make dline deduction for edges{j,j+1} */
2342 if (state->lines[e - g->edges] != LINE_UNKNOWN)
2343 /* Only worth doing this for an UNKNOWN,UNKNOWN pair.
2344 * Dlines where one of the edges is known, are handled in the
2348 dline_index = dline_index_from_face(g, f, k);
2352 /* minimum YESs in the complement of this dline */
2353 if (mins[k][j] > clue - 2) {
2354 /* Adding 2 YESs would break the clue */
2355 if (set_atmostone(dlines, dline_index))
2356 diff = min(diff, DIFF_NORMAL);
2358 /* maximum YESs in the complement of this dline */
2359 if (maxs[k][j] < clue) {
2360 /* Adding 2 NOs would mean not enough YESs */
2361 if (set_atleastone(dlines, dline_index))
2362 diff = min(diff, DIFF_NORMAL);
2368 if (diff < DIFF_NORMAL)
2371 /* ------ Dot deductions ------ */
2373 for (i = 0; i < g->num_dots; i++) {
2374 grid_dot *d = g->dots + i;
2376 int yes, no, unknown;
2378 if (sstate->dot_solved[i])
2380 yes = sstate->dot_yes_count[i];
2381 no = sstate->dot_no_count[i];
2382 unknown = N - yes - no;
2384 for (j = 0; j < N; j++) {
2387 int line1_index, line2_index;
2388 enum line_state line1, line2;
2391 dline_index = dline_index_from_dot(g, d, j);
2392 line1_index = d->edges[j] - g->edges;
2393 line2_index = d->edges[k] - g->edges;
2394 line1 = state->lines[line1_index];
2395 line2 = state->lines[line2_index];
2397 /* Infer dline state from line state */
2398 if (line1 == LINE_NO || line2 == LINE_NO) {
2399 if (set_atmostone(dlines, dline_index))
2400 diff = min(diff, DIFF_NORMAL);
2402 if (line1 == LINE_YES || line2 == LINE_YES) {
2403 if (set_atleastone(dlines, dline_index))
2404 diff = min(diff, DIFF_NORMAL);
2406 /* Infer line state from dline state */
2407 if (is_atmostone(dlines, dline_index)) {
2408 if (line1 == LINE_YES && line2 == LINE_UNKNOWN) {
2409 solver_set_line(sstate, line2_index, LINE_NO);
2410 diff = min(diff, DIFF_EASY);
2412 if (line2 == LINE_YES && line1 == LINE_UNKNOWN) {
2413 solver_set_line(sstate, line1_index, LINE_NO);
2414 diff = min(diff, DIFF_EASY);
2417 if (is_atleastone(dlines, dline_index)) {
2418 if (line1 == LINE_NO && line2 == LINE_UNKNOWN) {
2419 solver_set_line(sstate, line2_index, LINE_YES);
2420 diff = min(diff, DIFF_EASY);
2422 if (line2 == LINE_NO && line1 == LINE_UNKNOWN) {
2423 solver_set_line(sstate, line1_index, LINE_YES);
2424 diff = min(diff, DIFF_EASY);
2427 /* Deductions that depend on the numbers of lines.
2428 * Only bother if both lines are UNKNOWN, otherwise the
2429 * easy-mode solver (or deductions above) would have taken
2431 if (line1 != LINE_UNKNOWN || line2 != LINE_UNKNOWN)
2434 if (yes == 0 && unknown == 2) {
2435 /* Both these unknowns must be identical. If we know
2436 * atmostone or atleastone, we can make progress. */
2437 if (is_atmostone(dlines, dline_index)) {
2438 solver_set_line(sstate, line1_index, LINE_NO);
2439 solver_set_line(sstate, line2_index, LINE_NO);
2440 diff = min(diff, DIFF_EASY);
2442 if (is_atleastone(dlines, dline_index)) {
2443 solver_set_line(sstate, line1_index, LINE_YES);
2444 solver_set_line(sstate, line2_index, LINE_YES);
2445 diff = min(diff, DIFF_EASY);
2449 if (set_atmostone(dlines, dline_index))
2450 diff = min(diff, DIFF_NORMAL);
2452 if (set_atleastone(dlines, dline_index))
2453 diff = min(diff, DIFF_NORMAL);
2457 /* More advanced deduction that allows propagation along diagonal
2458 * chains of faces connected by dots, for example: 3-2-...-2-3
2459 * in square grids. */
2460 if (sstate->diff >= DIFF_TRICKY) {
2461 /* If we have atleastone set for this dline, infer
2462 * atmostone for each "opposite" dline (that is, each
2463 * dline without edges in common with this one).
2464 * Again, this test is only worth doing if both these
2465 * lines are UNKNOWN. For if one of these lines were YES,
2466 * the (yes == 1) test above would kick in instead. */
2467 if (is_atleastone(dlines, dline_index)) {
2469 for (opp = 0; opp < N; opp++) {
2470 int opp_dline_index;
2471 if (opp == j || opp == j+1 || opp == j-1)
2473 if (j == 0 && opp == N-1)
2475 if (j == N-1 && opp == 0)
2477 opp_dline_index = dline_index_from_dot(g, d, opp);
2478 if (set_atmostone(dlines, opp_dline_index))
2479 diff = min(diff, DIFF_NORMAL);
2481 if (yes == 0 && is_atmostone(dlines, dline_index)) {
2482 /* This dline has *exactly* one YES and there are no
2483 * other YESs. This allows more deductions. */
2485 /* Third unknown must be YES */
2486 for (opp = 0; opp < N; opp++) {
2488 if (opp == j || opp == k)
2490 opp_index = d->edges[opp] - g->edges;
2491 if (state->lines[opp_index] == LINE_UNKNOWN) {
2492 solver_set_line(sstate, opp_index,
2494 diff = min(diff, DIFF_EASY);
2497 } else if (unknown == 4) {
2498 /* Exactly one of opposite UNKNOWNS is YES. We've
2499 * already set atmostone, so set atleastone as
2502 if (dline_set_opp_atleastone(sstate, d, j))
2503 diff = min(diff, DIFF_NORMAL);
2513 static int linedsf_deductions(solver_state *sstate)
2515 game_state *state = sstate->state;
2516 grid *g = state->game_grid;
2517 char *dlines = sstate->dlines;
2519 int diff = DIFF_MAX;
2522 /* ------ Face deductions ------ */
2524 /* A fully-general linedsf deduction seems overly complicated
2525 * (I suspect the problem is NP-complete, though in practice it might just
2526 * be doable because faces are limited in size).
2527 * For simplicity, we only consider *pairs* of LINE_UNKNOWNS that are
2528 * known to be identical. If setting them both to YES (or NO) would break
2529 * the clue, set them to NO (or YES). */
2531 for (i = 0; i < g->num_faces; i++) {
2532 int N, yes, no, unknown;
2535 if (sstate->face_solved[i])
2537 clue = state->clues[i];
2541 N = g->faces[i].order;
2542 yes = sstate->face_yes_count[i];
2543 if (yes + 1 == clue) {
2544 if (face_setall_identical(sstate, i, LINE_NO))
2545 diff = min(diff, DIFF_EASY);
2547 no = sstate->face_no_count[i];
2548 if (no + 1 == N - clue) {
2549 if (face_setall_identical(sstate, i, LINE_YES))
2550 diff = min(diff, DIFF_EASY);
2553 /* Reload YES count, it might have changed */
2554 yes = sstate->face_yes_count[i];
2555 unknown = N - no - yes;
2557 /* Deductions with small number of LINE_UNKNOWNs, based on overall
2558 * parity of lines. */
2559 diff_tmp = parity_deductions(sstate, g->faces[i].edges,
2560 (clue - yes) % 2, unknown);
2561 diff = min(diff, diff_tmp);
2564 /* ------ Dot deductions ------ */
2565 for (i = 0; i < g->num_dots; i++) {
2566 grid_dot *d = g->dots + i;
2569 int yes, no, unknown;
2570 /* Go through dlines, and do any dline<->linedsf deductions wherever
2571 * we find two UNKNOWNS. */
2572 for (j = 0; j < N; j++) {
2573 int dline_index = dline_index_from_dot(g, d, j);
2576 int can1, can2, inv1, inv2;
2578 line1_index = d->edges[j] - g->edges;
2579 if (state->lines[line1_index] != LINE_UNKNOWN)
2582 if (j2 == N) j2 = 0;
2583 line2_index = d->edges[j2] - g->edges;
2584 if (state->lines[line2_index] != LINE_UNKNOWN)
2586 /* Infer dline flags from linedsf */
2587 can1 = edsf_canonify(sstate->linedsf, line1_index, &inv1);
2588 can2 = edsf_canonify(sstate->linedsf, line2_index, &inv2);
2589 if (can1 == can2 && inv1 != inv2) {
2590 /* These are opposites, so set dline atmostone/atleastone */
2591 if (set_atmostone(dlines, dline_index))
2592 diff = min(diff, DIFF_NORMAL);
2593 if (set_atleastone(dlines, dline_index))
2594 diff = min(diff, DIFF_NORMAL);
2597 /* Infer linedsf from dline flags */
2598 if (is_atmostone(dlines, dline_index)
2599 && is_atleastone(dlines, dline_index)) {
2600 if (merge_lines(sstate, line1_index, line2_index, 1))
2601 diff = min(diff, DIFF_HARD);
2605 /* Deductions with small number of LINE_UNKNOWNs, based on overall
2606 * parity of lines. */
2607 yes = sstate->dot_yes_count[i];
2608 no = sstate->dot_no_count[i];
2609 unknown = N - yes - no;
2610 diff_tmp = parity_deductions(sstate, d->edges,
2612 diff = min(diff, diff_tmp);
2615 /* ------ Edge dsf deductions ------ */
2617 /* If the state of a line is known, deduce the state of its canonical line
2618 * too, and vice versa. */
2619 for (i = 0; i < g->num_edges; i++) {
2622 can = edsf_canonify(sstate->linedsf, i, &inv);
2625 s = sstate->state->lines[can];
2626 if (s != LINE_UNKNOWN) {
2627 if (solver_set_line(sstate, i, inv ? OPP(s) : s))
2628 diff = min(diff, DIFF_EASY);
2630 s = sstate->state->lines[i];
2631 if (s != LINE_UNKNOWN) {
2632 if (solver_set_line(sstate, can, inv ? OPP(s) : s))
2633 diff = min(diff, DIFF_EASY);
2641 static int loop_deductions(solver_state *sstate)
2643 int edgecount = 0, clues = 0, satclues = 0, sm1clues = 0;
2644 game_state *state = sstate->state;
2645 grid *g = state->game_grid;
2646 int shortest_chainlen = g->num_dots;
2647 int loop_found = FALSE;
2649 int progress = FALSE;
2653 * Go through the grid and update for all the new edges.
2654 * Since merge_dots() is idempotent, the simplest way to
2655 * do this is just to update for _all_ the edges.
2656 * Also, while we're here, we count the edges.
2658 for (i = 0; i < g->num_edges; i++) {
2659 if (state->lines[i] == LINE_YES) {
2660 loop_found |= merge_dots(sstate, i);
2666 * Count the clues, count the satisfied clues, and count the
2667 * satisfied-minus-one clues.
2669 for (i = 0; i < g->num_faces; i++) {
2670 int c = state->clues[i];
2672 int o = sstate->face_yes_count[i];
2681 for (i = 0; i < g->num_dots; ++i) {
2683 sstate->looplen[dsf_canonify(sstate->dotdsf, i)];
2684 if (dots_connected > 1)
2685 shortest_chainlen = min(shortest_chainlen, dots_connected);
2688 assert(sstate->solver_status == SOLVER_INCOMPLETE);
2690 if (satclues == clues && shortest_chainlen == edgecount) {
2691 sstate->solver_status = SOLVER_SOLVED;
2692 /* This discovery clearly counts as progress, even if we haven't
2693 * just added any lines or anything */
2695 goto finished_loop_deductionsing;
2699 * Now go through looking for LINE_UNKNOWN edges which
2700 * connect two dots that are already in the same
2701 * equivalence class. If we find one, test to see if the
2702 * loop it would create is a solution.
2704 for (i = 0; i < g->num_edges; i++) {
2705 grid_edge *e = g->edges + i;
2706 int d1 = e->dot1 - g->dots;
2707 int d2 = e->dot2 - g->dots;
2709 if (state->lines[i] != LINE_UNKNOWN)
2712 eqclass = dsf_canonify(sstate->dotdsf, d1);
2713 if (eqclass != dsf_canonify(sstate->dotdsf, d2))
2716 val = LINE_NO; /* loop is bad until proven otherwise */
2719 * This edge would form a loop. Next
2720 * question: how long would the loop be?
2721 * Would it equal the total number of edges
2722 * (plus the one we'd be adding if we added
2725 if (sstate->looplen[eqclass] == edgecount + 1) {
2729 * This edge would form a loop which
2730 * took in all the edges in the entire
2731 * grid. So now we need to work out
2732 * whether it would be a valid solution
2733 * to the puzzle, which means we have to
2734 * check if it satisfies all the clues.
2735 * This means that every clue must be
2736 * either satisfied or satisfied-minus-
2737 * 1, and also that the number of
2738 * satisfied-minus-1 clues must be at
2739 * most two and they must lie on either
2740 * side of this edge.
2744 int f = e->face1 - g->faces;
2745 int c = state->clues[f];
2746 if (c >= 0 && sstate->face_yes_count[f] == c - 1)
2750 int f = e->face2 - g->faces;
2751 int c = state->clues[f];
2752 if (c >= 0 && sstate->face_yes_count[f] == c - 1)
2755 if (sm1clues == sm1_nearby &&
2756 sm1clues + satclues == clues) {
2757 val = LINE_YES; /* loop is good! */
2762 * Right. Now we know that adding this edge
2763 * would form a loop, and we know whether
2764 * that loop would be a viable solution or
2767 * If adding this edge produces a solution,
2768 * then we know we've found _a_ solution but
2769 * we don't know that it's _the_ solution -
2770 * if it were provably the solution then
2771 * we'd have deduced this edge some time ago
2772 * without the need to do loop detection. So
2773 * in this state we return SOLVER_AMBIGUOUS,
2774 * which has the effect that hitting Solve
2775 * on a user-provided puzzle will fill in a
2776 * solution but using the solver to
2777 * construct new puzzles won't consider this
2778 * a reasonable deduction for the user to
2781 progress = solver_set_line(sstate, i, val);
2782 assert(progress == TRUE);
2783 if (val == LINE_YES) {
2784 sstate->solver_status = SOLVER_AMBIGUOUS;
2785 goto finished_loop_deductionsing;
2789 finished_loop_deductionsing:
2790 return progress ? DIFF_EASY : DIFF_MAX;
2793 /* This will return a dynamically allocated solver_state containing the (more)
2795 static solver_state *solve_game_rec(const solver_state *sstate_start)
2797 solver_state *sstate;
2799 /* Index of the solver we should call next. */
2802 /* As a speed-optimisation, we avoid re-running solvers that we know
2803 * won't make any progress. This happens when a high-difficulty
2804 * solver makes a deduction that can only help other high-difficulty
2806 * For example: if a new 'dline' flag is set by dline_deductions, the
2807 * trivial_deductions solver cannot do anything with this information.
2808 * If we've already run the trivial_deductions solver (because it's
2809 * earlier in the list), there's no point running it again.
2811 * Therefore: if a solver is earlier in the list than "threshold_index",
2812 * we don't bother running it if it's difficulty level is less than
2815 int threshold_diff = 0;
2816 int threshold_index = 0;
2818 sstate = dup_solver_state(sstate_start);
2820 check_caches(sstate);
2822 while (i < NUM_SOLVERS) {
2823 if (sstate->solver_status == SOLVER_MISTAKE)
2825 if (sstate->solver_status == SOLVER_SOLVED ||
2826 sstate->solver_status == SOLVER_AMBIGUOUS) {
2827 /* solver finished */
2831 if ((solver_diffs[i] >= threshold_diff || i >= threshold_index)
2832 && solver_diffs[i] <= sstate->diff) {
2833 /* current_solver is eligible, so use it */
2834 int next_diff = solver_fns[i](sstate);
2835 if (next_diff != DIFF_MAX) {
2836 /* solver made progress, so use new thresholds and
2837 * start again at top of list. */
2838 threshold_diff = next_diff;
2839 threshold_index = i;
2844 /* current_solver is ineligible, or failed to make progress, so
2845 * go to the next solver in the list */
2849 if (sstate->solver_status == SOLVER_SOLVED ||
2850 sstate->solver_status == SOLVER_AMBIGUOUS) {
2851 /* s/LINE_UNKNOWN/LINE_NO/g */
2852 array_setall(sstate->state->lines, LINE_UNKNOWN, LINE_NO,
2853 sstate->state->game_grid->num_edges);
2860 static char *solve_game(const game_state *state, const game_state *currstate,
2861 const char *aux, char **error)
2864 solver_state *sstate, *new_sstate;
2866 sstate = new_solver_state(state, DIFF_MAX);
2867 new_sstate = solve_game_rec(sstate);
2869 if (new_sstate->solver_status == SOLVER_SOLVED) {
2870 soln = encode_solve_move(new_sstate->state);
2871 } else if (new_sstate->solver_status == SOLVER_AMBIGUOUS) {
2872 soln = encode_solve_move(new_sstate->state);
2873 /**error = "Solver found ambiguous solutions"; */
2875 soln = encode_solve_move(new_sstate->state);
2876 /**error = "Solver failed"; */
2879 free_solver_state(new_sstate);
2880 free_solver_state(sstate);
2885 /* ----------------------------------------------------------------------
2886 * Drawing and mouse-handling
2889 static char *interpret_move(const game_state *state, game_ui *ui,
2890 const game_drawstate *ds,
2891 int x, int y, int button)
2893 grid *g = state->game_grid;
2897 char button_char = ' ';
2898 enum line_state old_state;
2900 button &= ~MOD_MASK;
2902 /* Convert mouse-click (x,y) to grid coordinates */
2903 x -= BORDER(ds->tilesize);
2904 y -= BORDER(ds->tilesize);
2905 x = x * g->tilesize / ds->tilesize;
2906 y = y * g->tilesize / ds->tilesize;
2910 e = grid_nearest_edge(g, x, y);
2916 /* I think it's only possible to play this game with mouse clicks, sorry */
2917 /* Maybe will add mouse drag support some time */
2918 old_state = state->lines[i];
2922 switch (old_state) {
2940 switch (old_state) {
2959 sprintf(buf, "%d%c", i, (int)button_char);
2965 static game_state *execute_move(const game_state *state, const char *move)
2968 game_state *newstate = dup_game(state);
2970 if (move[0] == 'S') {
2972 newstate->cheated = TRUE;
2977 if (i < 0 || i >= newstate->game_grid->num_edges)
2979 move += strspn(move, "1234567890");
2980 switch (*(move++)) {
2982 newstate->lines[i] = LINE_YES;
2985 newstate->lines[i] = LINE_NO;
2988 newstate->lines[i] = LINE_UNKNOWN;
2996 * Check for completion.
2998 if (check_completion(newstate))
2999 newstate->solved = TRUE;
3004 free_game(newstate);
3008 /* ----------------------------------------------------------------------
3012 /* Convert from grid coordinates to screen coordinates */
3013 static void grid_to_screen(const game_drawstate *ds, const grid *g,
3014 int grid_x, int grid_y, int *x, int *y)
3016 *x = grid_x - g->lowest_x;
3017 *y = grid_y - g->lowest_y;
3018 *x = *x * ds->tilesize / g->tilesize;
3019 *y = *y * ds->tilesize / g->tilesize;
3020 *x += BORDER(ds->tilesize);
3021 *y += BORDER(ds->tilesize);
3024 /* Returns (into x,y) position of centre of face for rendering the text clue.
3026 static void face_text_pos(const game_drawstate *ds, const grid *g,
3027 grid_face *f, int *xret, int *yret)
3029 int faceindex = f - g->faces;
3032 * Return the cached position for this face, if we've already
3035 if (ds->textx[faceindex] >= 0) {
3036 *xret = ds->textx[faceindex];
3037 *yret = ds->texty[faceindex];
3042 * Otherwise, use the incentre computed by grid.c and convert it
3043 * to screen coordinates.
3045 grid_find_incentre(f);
3046 grid_to_screen(ds, g, f->ix, f->iy,
3047 &ds->textx[faceindex], &ds->texty[faceindex]);
3049 *xret = ds->textx[faceindex];
3050 *yret = ds->texty[faceindex];
3053 static void face_text_bbox(game_drawstate *ds, grid *g, grid_face *f,
3054 int *x, int *y, int *w, int *h)
3057 face_text_pos(ds, g, f, &xx, &yy);
3059 /* There seems to be a certain amount of trial-and-error involved
3060 * in working out the correct bounding-box for the text. */
3062 *x = xx - ds->tilesize/4 - 1;
3063 *y = yy - ds->tilesize/4 - 3;
3064 *w = ds->tilesize/2 + 2;
3065 *h = ds->tilesize/2 + 5;
3068 static void game_redraw_clue(drawing *dr, game_drawstate *ds,
3069 const game_state *state, int i)
3071 grid *g = state->game_grid;
3072 grid_face *f = g->faces + i;
3076 sprintf(c, "%d", state->clues[i]);
3078 face_text_pos(ds, g, f, &x, &y);
3080 FONT_VARIABLE, ds->tilesize/2,
3081 ALIGN_VCENTRE | ALIGN_HCENTRE,
3082 ds->clue_error[i] ? COL_MISTAKE :
3083 ds->clue_satisfied[i] ? COL_SATISFIED : COL_FOREGROUND, c);
3086 static void edge_bbox(game_drawstate *ds, grid *g, grid_edge *e,
3087 int *x, int *y, int *w, int *h)
3089 int x1 = e->dot1->x;
3090 int y1 = e->dot1->y;
3091 int x2 = e->dot2->x;
3092 int y2 = e->dot2->y;
3093 int xmin, xmax, ymin, ymax;
3095 grid_to_screen(ds, g, x1, y1, &x1, &y1);
3096 grid_to_screen(ds, g, x2, y2, &x2, &y2);
3097 /* Allow extra margin for dots, and thickness of lines */
3098 xmin = min(x1, x2) - 2;
3099 xmax = max(x1, x2) + 2;
3100 ymin = min(y1, y2) - 2;
3101 ymax = max(y1, y2) + 2;
3105 *w = xmax - xmin + 1;
3106 *h = ymax - ymin + 1;
3109 static void dot_bbox(game_drawstate *ds, grid *g, grid_dot *d,
3110 int *x, int *y, int *w, int *h)
3114 grid_to_screen(ds, g, d->x, d->y, &x1, &y1);
3122 static const int loopy_line_redraw_phases[] = {
3123 COL_FAINT, COL_LINEUNKNOWN, COL_FOREGROUND, COL_HIGHLIGHT, COL_MISTAKE
3125 #define NPHASES lenof(loopy_line_redraw_phases)
3127 static void game_redraw_line(drawing *dr, game_drawstate *ds,
3128 const game_state *state, int i, int phase)
3130 grid *g = state->game_grid;
3131 grid_edge *e = g->edges + i;
3135 if (state->line_errors[i])
3136 line_colour = COL_MISTAKE;
3137 else if (state->lines[i] == LINE_UNKNOWN)
3138 line_colour = COL_LINEUNKNOWN;
3139 else if (state->lines[i] == LINE_NO)
3140 line_colour = COL_FAINT;
3141 else if (ds->flashing)
3142 line_colour = COL_HIGHLIGHT;
3144 line_colour = COL_FOREGROUND;
3145 if (line_colour != loopy_line_redraw_phases[phase])
3148 /* Convert from grid to screen coordinates */
3149 grid_to_screen(ds, g, e->dot1->x, e->dot1->y, &x1, &y1);
3150 grid_to_screen(ds, g, e->dot2->x, e->dot2->y, &x2, &y2);
3152 if (line_colour == COL_FAINT) {
3153 static int draw_faint_lines = -1;
3154 if (draw_faint_lines < 0) {
3155 char *env = getenv("LOOPY_FAINT_LINES");
3156 draw_faint_lines = (!env || (env[0] == 'y' ||
3159 if (draw_faint_lines)
3160 draw_line(dr, x1, y1, x2, y2, line_colour);
3162 draw_thick_line(dr, 3.0,
3169 static void game_redraw_dot(drawing *dr, game_drawstate *ds,
3170 const game_state *state, int i)
3172 grid *g = state->game_grid;
3173 grid_dot *d = g->dots + i;
3176 grid_to_screen(ds, g, d->x, d->y, &x, &y);
3177 draw_circle(dr, x, y, 2, COL_FOREGROUND, COL_FOREGROUND);
3180 static int boxes_intersect(int x0, int y0, int w0, int h0,
3181 int x1, int y1, int w1, int h1)
3184 * Two intervals intersect iff neither is wholly on one side of
3185 * the other. Two boxes intersect iff their horizontal and
3186 * vertical intervals both intersect.
3188 return (x0 < x1+w1 && x1 < x0+w0 && y0 < y1+h1 && y1 < y0+h0);
3191 static void game_redraw_in_rect(drawing *dr, game_drawstate *ds,
3192 const game_state *state,
3193 int x, int y, int w, int h)
3195 grid *g = state->game_grid;
3199 clip(dr, x, y, w, h);
3200 draw_rect(dr, x, y, w, h, COL_BACKGROUND);
3202 for (i = 0; i < g->num_faces; i++) {
3203 if (state->clues[i] >= 0) {
3204 face_text_bbox(ds, g, &g->faces[i], &bx, &by, &bw, &bh);
3205 if (boxes_intersect(x, y, w, h, bx, by, bw, bh))
3206 game_redraw_clue(dr, ds, state, i);
3209 for (phase = 0; phase < NPHASES; phase++) {
3210 for (i = 0; i < g->num_edges; i++) {
3211 edge_bbox(ds, g, &g->edges[i], &bx, &by, &bw, &bh);
3212 if (boxes_intersect(x, y, w, h, bx, by, bw, bh))
3213 game_redraw_line(dr, ds, state, i, phase);
3216 for (i = 0; i < g->num_dots; i++) {
3217 dot_bbox(ds, g, &g->dots[i], &bx, &by, &bw, &bh);
3218 if (boxes_intersect(x, y, w, h, bx, by, bw, bh))
3219 game_redraw_dot(dr, ds, state, i);
3223 draw_update(dr, x, y, w, h);
3226 static void game_redraw(drawing *dr, game_drawstate *ds,
3227 const game_state *oldstate, const game_state *state,
3228 int dir, const game_ui *ui,
3229 float animtime, float flashtime)
3231 #define REDRAW_OBJECTS_LIMIT 16 /* Somewhat arbitrary tradeoff */
3233 grid *g = state->game_grid;
3234 int border = BORDER(ds->tilesize);
3237 int redraw_everything = FALSE;
3239 int edges[REDRAW_OBJECTS_LIMIT], nedges = 0;
3240 int faces[REDRAW_OBJECTS_LIMIT], nfaces = 0;
3242 /* Redrawing is somewhat involved.
3244 * An update can theoretically affect an arbitrary number of edges
3245 * (consider, for example, completing or breaking a cycle which doesn't
3246 * satisfy all the clues -- we'll switch many edges between error and
3247 * normal states). On the other hand, redrawing the whole grid takes a
3248 * while, making the game feel sluggish, and many updates are actually
3249 * quite well localized.
3251 * This redraw algorithm attempts to cope with both situations gracefully
3252 * and correctly. For localized changes, we set a clip rectangle, fill
3253 * it with background, and then redraw (a plausible but conservative
3254 * guess at) the objects which intersect the rectangle; if several
3255 * objects need redrawing, we'll do them individually. However, if lots
3256 * of objects are affected, we'll just redraw everything.
3258 * The reason for all of this is that it's just not safe to do the redraw
3259 * piecemeal. If you try to draw an antialiased diagonal line over
3260 * itself, you get a slightly thicker antialiased diagonal line, which
3261 * looks rather ugly after a while.
3263 * So, we take two passes over the grid. The first attempts to work out
3264 * what needs doing, and the second actually does it.
3268 redraw_everything = TRUE;
3270 * But we must still go through the upcoming loops, so that we
3271 * set up stuff in ds correctly for the initial redraw.
3275 /* First, trundle through the faces. */
3276 for (i = 0; i < g->num_faces; i++) {
3277 grid_face *f = g->faces + i;
3278 int sides = f->order;
3279 int yes_order, no_order;
3282 int n = state->clues[i];
3286 yes_order = face_order(state, i, LINE_YES);
3287 if (state->exactly_one_loop) {
3289 * Special case: if the set of LINE_YES edges in the grid
3290 * consists of exactly one loop and nothing else, then we
3291 * switch to treating LINE_UNKNOWN the same as LINE_NO for
3292 * purposes of clue checking.
3294 * This is because some people like to play Loopy without
3295 * using the right-click, i.e. never setting anything to
3296 * LINE_NO. Without this special case, if a person playing
3297 * in that style fills in what they think is a correct
3298 * solution loop but in fact it has an underfilled clue,
3299 * then we will display no victory flash and also no error
3300 * highlight explaining why not. With this special case,
3301 * we light up underfilled clues at the instant the loop
3302 * is closed. (Of course, *overfilled* clues are fine
3305 * (It might still be considered unfortunate that we can't
3306 * warn this style of player any earlier, if they make a
3307 * mistake very near the beginning which doesn't show up
3308 * until they close the last edge of the loop. One other
3309 * thing we _could_ do here is to treat any LINE_UNKNOWN
3310 * as LINE_NO if either of its endpoints has yes-degree 2,
3311 * reflecting the fact that setting that line to YES would
3312 * be an obvious error. But I don't think even that could
3313 * catch _all_ clue errors in a timely manner; I think
3314 * there are some that won't be displayed until the loop
3315 * is filled in, even so, and there's no way to avoid that
3316 * with complete reliability except to switch to being a
3317 * player who sets things to LINE_NO.)
3319 no_order = sides - yes_order;
3321 no_order = face_order(state, i, LINE_NO);
3324 clue_mistake = (yes_order > n || no_order > (sides-n));
3325 clue_satisfied = (yes_order == n && no_order == (sides-n));
3327 if (clue_mistake != ds->clue_error[i] ||
3328 clue_satisfied != ds->clue_satisfied[i]) {
3329 ds->clue_error[i] = clue_mistake;
3330 ds->clue_satisfied[i] = clue_satisfied;
3331 if (nfaces == REDRAW_OBJECTS_LIMIT)
3332 redraw_everything = TRUE;
3334 faces[nfaces++] = i;
3338 /* Work out what the flash state needs to be. */
3339 if (flashtime > 0 &&
3340 (flashtime <= FLASH_TIME/3 ||
3341 flashtime >= FLASH_TIME*2/3)) {
3342 flash_changed = !ds->flashing;
3343 ds->flashing = TRUE;
3345 flash_changed = ds->flashing;
3346 ds->flashing = FALSE;
3349 /* Now, trundle through the edges. */
3350 for (i = 0; i < g->num_edges; i++) {
3352 state->line_errors[i] ? DS_LINE_ERROR : state->lines[i];
3353 if (new_ds != ds->lines[i] ||
3354 (flash_changed && state->lines[i] == LINE_YES)) {
3355 ds->lines[i] = new_ds;
3356 if (nedges == REDRAW_OBJECTS_LIMIT)
3357 redraw_everything = TRUE;
3359 edges[nedges++] = i;
3363 /* Pass one is now done. Now we do the actual drawing. */
3364 if (redraw_everything) {
3365 int grid_width = g->highest_x - g->lowest_x;
3366 int grid_height = g->highest_y - g->lowest_y;
3367 int w = grid_width * ds->tilesize / g->tilesize;
3368 int h = grid_height * ds->tilesize / g->tilesize;
3370 game_redraw_in_rect(dr, ds, state,
3371 0, 0, w + 2*border + 1, h + 2*border + 1);
3374 /* Right. Now we roll up our sleeves. */
3376 for (i = 0; i < nfaces; i++) {
3377 grid_face *f = g->faces + faces[i];
3380 face_text_bbox(ds, g, f, &x, &y, &w, &h);
3381 game_redraw_in_rect(dr, ds, state, x, y, w, h);
3384 for (i = 0; i < nedges; i++) {
3385 grid_edge *e = g->edges + edges[i];
3388 edge_bbox(ds, g, e, &x, &y, &w, &h);
3389 game_redraw_in_rect(dr, ds, state, x, y, w, h);
3396 static float game_flash_length(const game_state *oldstate,
3397 const game_state *newstate, int dir, game_ui *ui)
3399 if (!oldstate->solved && newstate->solved &&
3400 !oldstate->cheated && !newstate->cheated) {
3407 static int game_status(const game_state *state)
3409 return state->solved ? +1 : 0;
3412 static void game_print_size(const game_params *params, float *x, float *y)
3417 * I'll use 7mm "squares" by default.
3419 game_compute_size(params, 700, &pw, &ph);
3424 static void game_print(drawing *dr, const game_state *state, int tilesize)
3426 int ink = print_mono_colour(dr, 0);
3428 game_drawstate ads, *ds = &ads;
3429 grid *g = state->game_grid;
3431 ds->tilesize = tilesize;
3432 ds->textx = snewn(g->num_faces, int);
3433 ds->texty = snewn(g->num_faces, int);
3434 for (i = 0; i < g->num_faces; i++)
3435 ds->textx[i] = ds->texty[i] = -1;
3437 for (i = 0; i < g->num_dots; i++) {
3439 grid_to_screen(ds, g, g->dots[i].x, g->dots[i].y, &x, &y);
3440 draw_circle(dr, x, y, ds->tilesize / 15, ink, ink);
3446 for (i = 0; i < g->num_faces; i++) {
3447 grid_face *f = g->faces + i;
3448 int clue = state->clues[i];
3452 sprintf(c, "%d", state->clues[i]);
3453 face_text_pos(ds, g, f, &x, &y);
3455 FONT_VARIABLE, ds->tilesize / 2,
3456 ALIGN_VCENTRE | ALIGN_HCENTRE, ink, c);
3463 for (i = 0; i < g->num_edges; i++) {
3464 int thickness = (state->lines[i] == LINE_YES) ? 30 : 150;
3465 grid_edge *e = g->edges + i;
3467 grid_to_screen(ds, g, e->dot1->x, e->dot1->y, &x1, &y1);
3468 grid_to_screen(ds, g, e->dot2->x, e->dot2->y, &x2, &y2);
3469 if (state->lines[i] == LINE_YES)
3471 /* (dx, dy) points from (x1, y1) to (x2, y2).
3472 * The line is then "fattened" in a perpendicular
3473 * direction to create a thin rectangle. */
3474 double d = sqrt(SQ((double)x1 - x2) + SQ((double)y1 - y2));
3475 double dx = (x2 - x1) / d;
3476 double dy = (y2 - y1) / d;
3479 dx = (dx * ds->tilesize) / thickness;
3480 dy = (dy * ds->tilesize) / thickness;
3481 points[0] = x1 + (int)dy;
3482 points[1] = y1 - (int)dx;
3483 points[2] = x1 - (int)dy;
3484 points[3] = y1 + (int)dx;
3485 points[4] = x2 - (int)dy;
3486 points[5] = y2 + (int)dx;
3487 points[6] = x2 + (int)dy;
3488 points[7] = y2 - (int)dx;
3489 draw_polygon(dr, points, 4, ink, ink);
3493 /* Draw a dotted line */
3496 for (j = 1; j < divisions; j++) {
3497 /* Weighted average */
3498 int x = (x1 * (divisions -j) + x2 * j) / divisions;
3499 int y = (y1 * (divisions -j) + y2 * j) / divisions;
3500 draw_circle(dr, x, y, ds->tilesize / thickness, ink, ink);
3510 #define thegame loopy
3513 const struct game thegame = {
3514 "Loopy", "games.loopy", "loopy",
3521 TRUE, game_configure, custom_params,
3529 TRUE, game_can_format_as_text_now, game_text_format,
3537 PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
3540 game_free_drawstate,
3545 TRUE, FALSE, game_print_size, game_print,
3546 FALSE /* wants_statusbar */,
3547 FALSE, game_timing_state,
3548 0, /* mouse_priorities */
3551 #ifdef STANDALONE_SOLVER
3554 * Half-hearted standalone solver. It can't output the solution to
3555 * anything but a square puzzle, and it can't log the deductions
3556 * it makes either. But it can solve square puzzles, and more
3557 * importantly it can use its solver to grade the difficulty of
3558 * any puzzle you give it.
3563 int main(int argc, char **argv)
3567 char *id = NULL, *desc, *err;
3570 #if 0 /* verbose solver not supported here (yet) */
3571 int really_verbose = FALSE;
3574 while (--argc > 0) {
3576 #if 0 /* verbose solver not supported here (yet) */
3577 if (!strcmp(p, "-v")) {
3578 really_verbose = TRUE;
3581 if (!strcmp(p, "-g")) {
3583 } else if (*p == '-') {
3584 fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
3592 fprintf(stderr, "usage: %s [-g | -v] <game_id>\n", argv[0]);
3596 desc = strchr(id, ':');
3598 fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
3603 p = default_params();
3604 decode_params(p, id);
3605 err = validate_desc(p, desc);
3607 fprintf(stderr, "%s: %s\n", argv[0], err);
3610 s = new_game(NULL, p, desc);
3613 * When solving an Easy puzzle, we don't want to bother the
3614 * user with Hard-level deductions. For this reason, we grade
3615 * the puzzle internally before doing anything else.
3617 ret = -1; /* placate optimiser */
3618 for (diff = 0; diff < DIFF_MAX; diff++) {
3619 solver_state *sstate_new;
3620 solver_state *sstate = new_solver_state((game_state *)s, diff);
3622 sstate_new = solve_game_rec(sstate);
3624 if (sstate_new->solver_status == SOLVER_MISTAKE)
3626 else if (sstate_new->solver_status == SOLVER_SOLVED)
3631 free_solver_state(sstate_new);
3632 free_solver_state(sstate);
3638 if (diff == DIFF_MAX) {
3640 printf("Difficulty rating: harder than Hard, or ambiguous\n");
3642 printf("Unable to find a unique solution\n");
3646 printf("Difficulty rating: impossible (no solution exists)\n");
3648 printf("Difficulty rating: %s\n", diffnames[diff]);
3650 solver_state *sstate_new;
3651 solver_state *sstate = new_solver_state((game_state *)s, diff);
3653 /* If we supported a verbose solver, we'd set verbosity here */
3655 sstate_new = solve_game_rec(sstate);
3657 if (sstate_new->solver_status == SOLVER_MISTAKE)
3658 printf("Puzzle is inconsistent\n");
3660 assert(sstate_new->solver_status == SOLVER_SOLVED);
3661 if (s->grid_type == 0) {
3662 fputs(game_text_format(sstate_new->state), stdout);
3664 printf("Unable to output non-square grids\n");
3668 free_solver_state(sstate_new);
3669 free_solver_state(sstate);
3678 /* vim: set shiftwidth=4 tabstop=8: */