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;
125 /* Used in game_text_format(), so that it knows what type of
126 * grid it's trying to render as ASCII text. */
131 SOLVER_SOLVED, /* This is the only solution the solver could find */
132 SOLVER_MISTAKE, /* This is definitely not a solution */
133 SOLVER_AMBIGUOUS, /* This _might_ be an ambiguous solution */
134 SOLVER_INCOMPLETE /* This may be a partial solution */
137 /* ------ Solver state ------ */
138 typedef struct solver_state {
140 enum solver_status solver_status;
141 /* NB looplen is the number of dots that are joined together at a point, ie a
142 * looplen of 1 means there are no lines to a particular dot */
145 /* Difficulty level of solver. Used by solver functions that want to
146 * vary their behaviour depending on the requested difficulty level. */
152 char *face_yes_count;
154 char *dot_solved, *face_solved;
157 /* Information for Normal level deductions:
158 * For each dline, store a bitmask for whether we know:
159 * (bit 0) at least one is YES
160 * (bit 1) at most one is YES */
163 /* Hard level information */
168 * Difficulty levels. I do some macro ickery here to ensure that my
169 * enum and the various forms of my name list always match up.
172 #define DIFFLIST(A) \
177 #define ENUM(upper,title,lower) DIFF_ ## upper,
178 #define TITLE(upper,title,lower) #title,
179 #define ENCODE(upper,title,lower) #lower
180 #define CONFIG(upper,title,lower) ":" #title
181 enum { DIFFLIST(ENUM) DIFF_MAX };
182 static char const *const diffnames[] = { DIFFLIST(TITLE) };
183 static char const diffchars[] = DIFFLIST(ENCODE);
184 #define DIFFCONFIG DIFFLIST(CONFIG)
187 * Solver routines, sorted roughly in order of computational cost.
188 * The solver will run the faster deductions first, and slower deductions are
189 * only invoked when the faster deductions are unable to make progress.
190 * Each function is associated with a difficulty level, so that the generated
191 * puzzles are solvable by applying only the functions with the chosen
192 * difficulty level or lower.
194 #define SOLVERLIST(A) \
195 A(trivial_deductions, DIFF_EASY) \
196 A(dline_deductions, DIFF_NORMAL) \
197 A(linedsf_deductions, DIFF_HARD) \
198 A(loop_deductions, DIFF_EASY)
199 #define SOLVER_FN_DECL(fn,diff) static int fn(solver_state *);
200 #define SOLVER_FN(fn,diff) &fn,
201 #define SOLVER_DIFF(fn,diff) diff,
202 SOLVERLIST(SOLVER_FN_DECL)
203 static int (*(solver_fns[]))(solver_state *) = { SOLVERLIST(SOLVER_FN) };
204 static int const solver_diffs[] = { SOLVERLIST(SOLVER_DIFF) };
205 static const int NUM_SOLVERS = sizeof(solver_diffs)/sizeof(*solver_diffs);
213 /* line_drawstate is the same as line_state, but with the extra ERROR
214 * possibility. The drawing code copies line_state to line_drawstate,
215 * except in the case that the line is an error. */
216 enum line_state { LINE_YES, LINE_UNKNOWN, LINE_NO };
217 enum line_drawstate { DS_LINE_YES, DS_LINE_UNKNOWN,
218 DS_LINE_NO, DS_LINE_ERROR };
220 #define OPP(line_state) \
224 struct game_drawstate {
231 char *clue_satisfied;
234 static char *validate_desc(const game_params *params, const char *desc);
235 static int dot_order(const game_state* state, int i, char line_type);
236 static int face_order(const game_state* state, int i, char line_type);
237 static solver_state *solve_game_rec(const solver_state *sstate);
240 static void check_caches(const solver_state* sstate);
242 #define check_caches(s)
245 /* ------- List of grid generators ------- */
246 #define GRIDLIST(A) \
247 A(Squares,GRID_SQUARE,3,3) \
248 A(Triangular,GRID_TRIANGULAR,3,3) \
249 A(Honeycomb,GRID_HONEYCOMB,3,3) \
250 A(Snub-Square,GRID_SNUBSQUARE,3,3) \
251 A(Cairo,GRID_CAIRO,3,4) \
252 A(Great-Hexagonal,GRID_GREATHEXAGONAL,3,3) \
253 A(Octagonal,GRID_OCTAGONAL,3,3) \
254 A(Kites,GRID_KITE,3,3) \
255 A(Floret,GRID_FLORET,1,2) \
256 A(Dodecagonal,GRID_DODECAGONAL,2,2) \
257 A(Great-Dodecagonal,GRID_GREATDODECAGONAL,2,2) \
258 A(Penrose (kite/dart),GRID_PENROSE_P2,3,3) \
259 A(Penrose (rhombs),GRID_PENROSE_P3,3,3)
261 #define GRID_NAME(title,type,amin,omin) #title,
262 #define GRID_CONFIG(title,type,amin,omin) ":" #title
263 #define GRID_TYPE(title,type,amin,omin) type,
264 #define GRID_SIZES(title,type,amin,omin) \
266 "Width and height for this grid type must both be at least " #amin, \
267 "At least one of width and height for this grid type must be at least " #omin,},
268 static char const *const gridnames[] = { GRIDLIST(GRID_NAME) };
269 #define GRID_CONFIGS GRIDLIST(GRID_CONFIG)
270 static grid_type grid_types[] = { GRIDLIST(GRID_TYPE) };
271 #define NUM_GRID_TYPES (sizeof(grid_types) / sizeof(grid_types[0]))
272 static const struct {
275 } grid_size_limits[] = { GRIDLIST(GRID_SIZES) };
277 /* Generates a (dynamically allocated) new grid, according to the
278 * type and size requested in params. Does nothing if the grid is already
280 static grid *loopy_generate_grid(const game_params *params,
281 const char *grid_desc)
283 return grid_new(grid_types[params->type], params->w, params->h, grid_desc);
286 /* ----------------------------------------------------------------------
290 /* General constants */
291 #define PREFERRED_TILE_SIZE 32
292 #define BORDER(tilesize) ((tilesize) / 2)
293 #define FLASH_TIME 0.5F
295 #define BIT_SET(field, bit) ((field) & (1<<(bit)))
297 #define SET_BIT(field, bit) (BIT_SET(field, bit) ? FALSE : \
298 ((field) |= (1<<(bit)), TRUE))
300 #define CLEAR_BIT(field, bit) (BIT_SET(field, bit) ? \
301 ((field) &= ~(1<<(bit)), TRUE) : FALSE)
303 #define CLUE2CHAR(c) \
304 ((c < 0) ? ' ' : c < 10 ? c + '0' : c - 10 + 'A')
306 /* ----------------------------------------------------------------------
307 * General struct manipulation and other straightforward code
310 static game_state *dup_game(const game_state *state)
312 game_state *ret = snew(game_state);
314 ret->game_grid = state->game_grid;
315 ret->game_grid->refcount++;
317 ret->solved = state->solved;
318 ret->cheated = state->cheated;
320 ret->clues = snewn(state->game_grid->num_faces, signed char);
321 memcpy(ret->clues, state->clues, state->game_grid->num_faces);
323 ret->lines = snewn(state->game_grid->num_edges, char);
324 memcpy(ret->lines, state->lines, state->game_grid->num_edges);
326 ret->line_errors = snewn(state->game_grid->num_edges, unsigned char);
327 memcpy(ret->line_errors, state->line_errors, state->game_grid->num_edges);
329 ret->grid_type = state->grid_type;
333 static void free_game(game_state *state)
336 grid_free(state->game_grid);
339 sfree(state->line_errors);
344 static solver_state *new_solver_state(const game_state *state, int diff) {
346 int num_dots = state->game_grid->num_dots;
347 int num_faces = state->game_grid->num_faces;
348 int num_edges = state->game_grid->num_edges;
349 solver_state *ret = snew(solver_state);
351 ret->state = dup_game(state);
353 ret->solver_status = SOLVER_INCOMPLETE;
356 ret->dotdsf = snew_dsf(num_dots);
357 ret->looplen = snewn(num_dots, int);
359 for (i = 0; i < num_dots; i++) {
363 ret->dot_solved = snewn(num_dots, char);
364 ret->face_solved = snewn(num_faces, char);
365 memset(ret->dot_solved, FALSE, num_dots);
366 memset(ret->face_solved, FALSE, num_faces);
368 ret->dot_yes_count = snewn(num_dots, char);
369 memset(ret->dot_yes_count, 0, num_dots);
370 ret->dot_no_count = snewn(num_dots, char);
371 memset(ret->dot_no_count, 0, num_dots);
372 ret->face_yes_count = snewn(num_faces, char);
373 memset(ret->face_yes_count, 0, num_faces);
374 ret->face_no_count = snewn(num_faces, char);
375 memset(ret->face_no_count, 0, num_faces);
377 if (diff < DIFF_NORMAL) {
380 ret->dlines = snewn(2*num_edges, char);
381 memset(ret->dlines, 0, 2*num_edges);
384 if (diff < DIFF_HARD) {
387 ret->linedsf = snew_dsf(state->game_grid->num_edges);
393 static void free_solver_state(solver_state *sstate) {
395 free_game(sstate->state);
396 sfree(sstate->dotdsf);
397 sfree(sstate->looplen);
398 sfree(sstate->dot_solved);
399 sfree(sstate->face_solved);
400 sfree(sstate->dot_yes_count);
401 sfree(sstate->dot_no_count);
402 sfree(sstate->face_yes_count);
403 sfree(sstate->face_no_count);
405 /* OK, because sfree(NULL) is a no-op */
406 sfree(sstate->dlines);
407 sfree(sstate->linedsf);
413 static solver_state *dup_solver_state(const solver_state *sstate) {
414 game_state *state = sstate->state;
415 int num_dots = state->game_grid->num_dots;
416 int num_faces = state->game_grid->num_faces;
417 int num_edges = state->game_grid->num_edges;
418 solver_state *ret = snew(solver_state);
420 ret->state = state = dup_game(sstate->state);
422 ret->solver_status = sstate->solver_status;
423 ret->diff = sstate->diff;
425 ret->dotdsf = snewn(num_dots, int);
426 ret->looplen = snewn(num_dots, int);
427 memcpy(ret->dotdsf, sstate->dotdsf,
428 num_dots * sizeof(int));
429 memcpy(ret->looplen, sstate->looplen,
430 num_dots * sizeof(int));
432 ret->dot_solved = snewn(num_dots, char);
433 ret->face_solved = snewn(num_faces, char);
434 memcpy(ret->dot_solved, sstate->dot_solved, num_dots);
435 memcpy(ret->face_solved, sstate->face_solved, num_faces);
437 ret->dot_yes_count = snewn(num_dots, char);
438 memcpy(ret->dot_yes_count, sstate->dot_yes_count, num_dots);
439 ret->dot_no_count = snewn(num_dots, char);
440 memcpy(ret->dot_no_count, sstate->dot_no_count, num_dots);
442 ret->face_yes_count = snewn(num_faces, char);
443 memcpy(ret->face_yes_count, sstate->face_yes_count, num_faces);
444 ret->face_no_count = snewn(num_faces, char);
445 memcpy(ret->face_no_count, sstate->face_no_count, num_faces);
447 if (sstate->dlines) {
448 ret->dlines = snewn(2*num_edges, char);
449 memcpy(ret->dlines, sstate->dlines,
455 if (sstate->linedsf) {
456 ret->linedsf = snewn(num_edges, int);
457 memcpy(ret->linedsf, sstate->linedsf,
458 num_edges * sizeof(int));
466 static game_params *default_params(void)
468 game_params *ret = snew(game_params);
477 ret->diff = DIFF_EASY;
483 static game_params *dup_params(const game_params *params)
485 game_params *ret = snew(game_params);
487 *ret = *params; /* structure copy */
491 static const game_params presets[] = {
493 { 7, 7, DIFF_EASY, 0 },
494 { 7, 7, DIFF_NORMAL, 0 },
495 { 7, 7, DIFF_HARD, 0 },
496 { 7, 7, DIFF_HARD, 1 },
497 { 7, 7, DIFF_HARD, 2 },
498 { 5, 5, DIFF_HARD, 3 },
499 { 7, 7, DIFF_HARD, 4 },
500 { 5, 4, DIFF_HARD, 5 },
501 { 5, 5, DIFF_HARD, 6 },
502 { 5, 5, DIFF_HARD, 7 },
503 { 3, 3, DIFF_HARD, 8 },
504 { 3, 3, DIFF_HARD, 9 },
505 { 3, 3, DIFF_HARD, 10 },
506 { 6, 6, DIFF_HARD, 11 },
507 { 6, 6, DIFF_HARD, 12 },
509 { 7, 7, DIFF_EASY, 0 },
510 { 10, 10, DIFF_EASY, 0 },
511 { 7, 7, DIFF_NORMAL, 0 },
512 { 10, 10, DIFF_NORMAL, 0 },
513 { 7, 7, DIFF_HARD, 0 },
514 { 10, 10, DIFF_HARD, 0 },
515 { 10, 10, DIFF_HARD, 1 },
516 { 12, 10, DIFF_HARD, 2 },
517 { 7, 7, DIFF_HARD, 3 },
518 { 9, 9, DIFF_HARD, 4 },
519 { 5, 4, DIFF_HARD, 5 },
520 { 7, 7, DIFF_HARD, 6 },
521 { 5, 5, DIFF_HARD, 7 },
522 { 5, 5, DIFF_HARD, 8 },
523 { 5, 4, DIFF_HARD, 9 },
524 { 5, 4, DIFF_HARD, 10 },
525 { 10, 10, DIFF_HARD, 11 },
526 { 10, 10, DIFF_HARD, 12 }
530 static int game_fetch_preset(int i, char **name, game_params **params)
535 if (i < 0 || i >= lenof(presets))
538 tmppar = snew(game_params);
539 *tmppar = presets[i];
541 sprintf(buf, "%dx%d %s - %s", tmppar->h, tmppar->w,
542 gridnames[tmppar->type], diffnames[tmppar->diff]);
548 static void free_params(game_params *params)
553 static void decode_params(game_params *params, char const *string)
555 params->h = params->w = atoi(string);
556 params->diff = DIFF_EASY;
557 while (*string && isdigit((unsigned char)*string)) string++;
558 if (*string == 'x') {
560 params->h = atoi(string);
561 while (*string && isdigit((unsigned char)*string)) string++;
563 if (*string == 't') {
565 params->type = atoi(string);
566 while (*string && isdigit((unsigned char)*string)) string++;
568 if (*string == 'd') {
571 for (i = 0; i < DIFF_MAX; i++)
572 if (*string == diffchars[i])
574 if (*string) string++;
578 static char *encode_params(const game_params *params, int full)
581 sprintf(str, "%dx%dt%d", params->w, params->h, params->type);
583 sprintf(str + strlen(str), "d%c", diffchars[params->diff]);
587 static config_item *game_configure(const game_params *params)
592 ret = snewn(5, config_item);
594 ret[0].name = "Width";
595 ret[0].type = C_STRING;
596 sprintf(buf, "%d", params->w);
597 ret[0].sval = dupstr(buf);
600 ret[1].name = "Height";
601 ret[1].type = C_STRING;
602 sprintf(buf, "%d", params->h);
603 ret[1].sval = dupstr(buf);
606 ret[2].name = "Grid type";
607 ret[2].type = C_CHOICES;
608 ret[2].sval = GRID_CONFIGS;
609 ret[2].ival = params->type;
611 ret[3].name = "Difficulty";
612 ret[3].type = C_CHOICES;
613 ret[3].sval = DIFFCONFIG;
614 ret[3].ival = params->diff;
624 static game_params *custom_params(const config_item *cfg)
626 game_params *ret = snew(game_params);
628 ret->w = atoi(cfg[0].sval);
629 ret->h = atoi(cfg[1].sval);
630 ret->type = cfg[2].ival;
631 ret->diff = cfg[3].ival;
636 static char *validate_params(const game_params *params, int full)
638 if (params->type < 0 || params->type >= NUM_GRID_TYPES)
639 return "Illegal grid type";
640 if (params->w < grid_size_limits[params->type].amin ||
641 params->h < grid_size_limits[params->type].amin)
642 return grid_size_limits[params->type].aerr;
643 if (params->w < grid_size_limits[params->type].omin &&
644 params->h < grid_size_limits[params->type].omin)
645 return grid_size_limits[params->type].oerr;
648 * This shouldn't be able to happen at all, since decode_params
649 * and custom_params will never generate anything that isn't
652 assert(params->diff < DIFF_MAX);
657 /* Returns a newly allocated string describing the current puzzle */
658 static char *state_to_text(const game_state *state)
660 grid *g = state->game_grid;
662 int num_faces = g->num_faces;
663 char *description = snewn(num_faces + 1, char);
664 char *dp = description;
668 for (i = 0; i < num_faces; i++) {
669 if (state->clues[i] < 0) {
670 if (empty_count > 25) {
671 dp += sprintf(dp, "%c", (int)(empty_count + 'a' - 1));
677 dp += sprintf(dp, "%c", (int)(empty_count + 'a' - 1));
680 dp += sprintf(dp, "%c", (int)CLUE2CHAR(state->clues[i]));
685 dp += sprintf(dp, "%c", (int)(empty_count + 'a' - 1));
687 retval = dupstr(description);
693 #define GRID_DESC_SEP '_'
695 /* Splits up a (optional) grid_desc from the game desc. Returns the
696 * grid_desc (which needs freeing) and updates the desc pointer to
697 * start of real desc, or returns NULL if no desc. */
698 static char *extract_grid_desc(const char **desc)
700 char *sep = strchr(*desc, GRID_DESC_SEP), *gd;
703 if (!sep) return NULL;
705 gd_len = sep - (*desc);
706 gd = snewn(gd_len+1, char);
707 memcpy(gd, *desc, gd_len);
715 /* We require that the params pass the test in validate_params and that the
716 * description fills the entire game area */
717 static char *validate_desc(const game_params *params, const char *desc)
721 char *grid_desc, *ret;
723 /* It's pretty inefficient to do this just for validation. All we need to
724 * know is the precise number of faces. */
725 grid_desc = extract_grid_desc(&desc);
726 ret = grid_validate_desc(grid_types[params->type], params->w, params->h, grid_desc);
729 g = loopy_generate_grid(params, grid_desc);
730 if (grid_desc) sfree(grid_desc);
732 for (; *desc; ++desc) {
733 if ((*desc >= '0' && *desc <= '9') || (*desc >= 'A' && *desc <= 'Z')) {
738 count += *desc - 'a' + 1;
741 return "Unknown character in description";
744 if (count < g->num_faces)
745 return "Description too short for board size";
746 if (count > g->num_faces)
747 return "Description too long for board size";
754 /* Sums the lengths of the numbers in range [0,n) */
755 /* See equivalent function in solo.c for justification of this. */
756 static int len_0_to_n(int n)
758 int len = 1; /* Counting 0 as a bit of a special case */
761 for (i = 1; i < n; i *= 10) {
762 len += max(n - i, 0);
768 static char *encode_solve_move(const game_state *state)
773 int num_edges = state->game_grid->num_edges;
775 /* This is going to return a string representing the moves needed to set
776 * every line in a grid to be the same as the ones in 'state'. The exact
777 * length of this string is predictable. */
779 len = 1; /* Count the 'S' prefix */
780 /* Numbers in all lines */
781 len += len_0_to_n(num_edges);
782 /* For each line we also have a letter */
785 ret = snewn(len + 1, char);
788 p += sprintf(p, "S");
790 for (i = 0; i < num_edges; i++) {
791 switch (state->lines[i]) {
793 p += sprintf(p, "%dy", i);
796 p += sprintf(p, "%dn", i);
801 /* No point in doing sums like that if they're going to be wrong */
802 assert(strlen(ret) <= (size_t)len);
806 static game_ui *new_ui(const game_state *state)
811 static void free_ui(game_ui *ui)
815 static char *encode_ui(const game_ui *ui)
820 static void decode_ui(game_ui *ui, const char *encoding)
824 static void game_changed_state(game_ui *ui, const game_state *oldstate,
825 const game_state *newstate)
829 static void game_compute_size(const game_params *params, int tilesize,
832 int grid_width, grid_height, rendered_width, rendered_height;
835 grid_compute_size(grid_types[params->type], params->w, params->h,
836 &g_tilesize, &grid_width, &grid_height);
838 /* multiply first to minimise rounding error on integer division */
839 rendered_width = grid_width * tilesize / g_tilesize;
840 rendered_height = grid_height * tilesize / g_tilesize;
841 *x = rendered_width + 2 * BORDER(tilesize) + 1;
842 *y = rendered_height + 2 * BORDER(tilesize) + 1;
845 static void game_set_size(drawing *dr, game_drawstate *ds,
846 const game_params *params, int tilesize)
848 ds->tilesize = tilesize;
851 static float *game_colours(frontend *fe, int *ncolours)
853 float *ret = snewn(4 * NCOLOURS, float);
855 frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
857 ret[COL_FOREGROUND * 3 + 0] = 0.0F;
858 ret[COL_FOREGROUND * 3 + 1] = 0.0F;
859 ret[COL_FOREGROUND * 3 + 2] = 0.0F;
862 * We want COL_LINEUNKNOWN to be a yellow which is a bit darker
863 * than the background. (I previously set it to 0.8,0.8,0, but
864 * found that this went badly with the 0.8,0.8,0.8 favoured as a
865 * background by the Java frontend.)
867 ret[COL_LINEUNKNOWN * 3 + 0] = ret[COL_BACKGROUND * 3 + 0] * 0.9F;
868 ret[COL_LINEUNKNOWN * 3 + 1] = ret[COL_BACKGROUND * 3 + 1] * 0.9F;
869 ret[COL_LINEUNKNOWN * 3 + 2] = 0.0F;
871 ret[COL_HIGHLIGHT * 3 + 0] = 1.0F;
872 ret[COL_HIGHLIGHT * 3 + 1] = 1.0F;
873 ret[COL_HIGHLIGHT * 3 + 2] = 1.0F;
875 ret[COL_MISTAKE * 3 + 0] = 1.0F;
876 ret[COL_MISTAKE * 3 + 1] = 0.0F;
877 ret[COL_MISTAKE * 3 + 2] = 0.0F;
879 ret[COL_SATISFIED * 3 + 0] = 0.0F;
880 ret[COL_SATISFIED * 3 + 1] = 0.0F;
881 ret[COL_SATISFIED * 3 + 2] = 0.0F;
883 /* We want the faint lines to be a bit darker than the background.
884 * Except if the background is pretty dark already; then it ought to be a
885 * bit lighter. Oy vey.
887 ret[COL_FAINT * 3 + 0] = ret[COL_BACKGROUND * 3 + 0] * 0.9F;
888 ret[COL_FAINT * 3 + 1] = ret[COL_BACKGROUND * 3 + 1] * 0.9F;
889 ret[COL_FAINT * 3 + 2] = ret[COL_BACKGROUND * 3 + 2] * 0.9F;
891 *ncolours = NCOLOURS;
895 static game_drawstate *game_new_drawstate(drawing *dr, const game_state *state)
897 struct game_drawstate *ds = snew(struct game_drawstate);
898 int num_faces = state->game_grid->num_faces;
899 int num_edges = state->game_grid->num_edges;
904 ds->lines = snewn(num_edges, char);
905 ds->clue_error = snewn(num_faces, char);
906 ds->clue_satisfied = snewn(num_faces, char);
907 ds->textx = snewn(num_faces, int);
908 ds->texty = snewn(num_faces, int);
911 memset(ds->lines, LINE_UNKNOWN, num_edges);
912 memset(ds->clue_error, 0, num_faces);
913 memset(ds->clue_satisfied, 0, num_faces);
914 for (i = 0; i < num_faces; i++)
915 ds->textx[i] = ds->texty[i] = -1;
920 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
924 sfree(ds->clue_error);
925 sfree(ds->clue_satisfied);
930 static int game_timing_state(const game_state *state, game_ui *ui)
935 static float game_anim_length(const game_state *oldstate,
936 const game_state *newstate, int dir, game_ui *ui)
941 static int game_can_format_as_text_now(const game_params *params)
943 if (params->type != 0)
948 static char *game_text_format(const game_state *state)
954 grid *g = state->game_grid;
957 assert(state->grid_type == 0);
959 /* Work out the basic size unit */
960 f = g->faces; /* first face */
961 assert(f->order == 4);
962 /* The dots are ordered clockwise, so the two opposite
963 * corners are guaranteed to span the square */
964 cell_size = abs(f->dots[0]->x - f->dots[2]->x);
966 w = (g->highest_x - g->lowest_x) / cell_size;
967 h = (g->highest_y - g->lowest_y) / cell_size;
969 /* Create a blank "canvas" to "draw" on */
972 ret = snewn(W * H + 1, char);
973 for (y = 0; y < H; y++) {
974 for (x = 0; x < W-1; x++) {
977 ret[y*W + W-1] = '\n';
981 /* Fill in edge info */
982 for (i = 0; i < g->num_edges; i++) {
983 grid_edge *e = g->edges + i;
984 /* Cell coordinates, from (0,0) to (w-1,h-1) */
985 int x1 = (e->dot1->x - g->lowest_x) / cell_size;
986 int x2 = (e->dot2->x - g->lowest_x) / cell_size;
987 int y1 = (e->dot1->y - g->lowest_y) / cell_size;
988 int y2 = (e->dot2->y - g->lowest_y) / cell_size;
989 /* Midpoint, in canvas coordinates (canvas coordinates are just twice
990 * cell coordinates) */
993 switch (state->lines[i]) {
995 ret[y*W + x] = (y1 == y2) ? '-' : '|';
1001 break; /* already a space */
1003 assert(!"Illegal line state");
1008 for (i = 0; i < g->num_faces; i++) {
1012 assert(f->order == 4);
1013 /* Cell coordinates, from (0,0) to (w-1,h-1) */
1014 x1 = (f->dots[0]->x - g->lowest_x) / cell_size;
1015 x2 = (f->dots[2]->x - g->lowest_x) / cell_size;
1016 y1 = (f->dots[0]->y - g->lowest_y) / cell_size;
1017 y2 = (f->dots[2]->y - g->lowest_y) / cell_size;
1018 /* Midpoint, in canvas coordinates */
1021 ret[y*W + x] = CLUE2CHAR(state->clues[i]);
1026 /* ----------------------------------------------------------------------
1031 static void check_caches(const solver_state* sstate)
1034 const game_state *state = sstate->state;
1035 const grid *g = state->game_grid;
1037 for (i = 0; i < g->num_dots; i++) {
1038 assert(dot_order(state, i, LINE_YES) == sstate->dot_yes_count[i]);
1039 assert(dot_order(state, i, LINE_NO) == sstate->dot_no_count[i]);
1042 for (i = 0; i < g->num_faces; i++) {
1043 assert(face_order(state, i, LINE_YES) == sstate->face_yes_count[i]);
1044 assert(face_order(state, i, LINE_NO) == sstate->face_no_count[i]);
1049 #define check_caches(s) \
1051 fprintf(stderr, "check_caches at line %d\n", __LINE__); \
1055 #endif /* DEBUG_CACHES */
1057 /* ----------------------------------------------------------------------
1058 * Solver utility functions
1061 /* Sets the line (with index i) to the new state 'line_new', and updates
1062 * the cached counts of any affected faces and dots.
1063 * Returns TRUE if this actually changed the line's state. */
1064 static int solver_set_line(solver_state *sstate, int i,
1065 enum line_state line_new
1067 , const char *reason
1071 game_state *state = sstate->state;
1075 assert(line_new != LINE_UNKNOWN);
1077 check_caches(sstate);
1079 if (state->lines[i] == line_new) {
1080 return FALSE; /* nothing changed */
1082 state->lines[i] = line_new;
1085 fprintf(stderr, "solver: set line [%d] to %s (%s)\n",
1086 i, line_new == LINE_YES ? "YES" : "NO",
1090 g = state->game_grid;
1093 /* Update the cache for both dots and both faces affected by this. */
1094 if (line_new == LINE_YES) {
1095 sstate->dot_yes_count[e->dot1 - g->dots]++;
1096 sstate->dot_yes_count[e->dot2 - g->dots]++;
1098 sstate->face_yes_count[e->face1 - g->faces]++;
1101 sstate->face_yes_count[e->face2 - g->faces]++;
1104 sstate->dot_no_count[e->dot1 - g->dots]++;
1105 sstate->dot_no_count[e->dot2 - g->dots]++;
1107 sstate->face_no_count[e->face1 - g->faces]++;
1110 sstate->face_no_count[e->face2 - g->faces]++;
1114 check_caches(sstate);
1119 #define solver_set_line(a, b, c) \
1120 solver_set_line(a, b, c, __FUNCTION__)
1124 * Merge two dots due to the existence of an edge between them.
1125 * Updates the dsf tracking equivalence classes, and keeps track of
1126 * the length of path each dot is currently a part of.
1127 * Returns TRUE if the dots were already linked, ie if they are part of a
1128 * closed loop, and false otherwise.
1130 static int merge_dots(solver_state *sstate, int edge_index)
1133 grid *g = sstate->state->game_grid;
1134 grid_edge *e = g->edges + edge_index;
1136 i = e->dot1 - g->dots;
1137 j = e->dot2 - g->dots;
1139 i = dsf_canonify(sstate->dotdsf, i);
1140 j = dsf_canonify(sstate->dotdsf, j);
1145 len = sstate->looplen[i] + sstate->looplen[j];
1146 dsf_merge(sstate->dotdsf, i, j);
1147 i = dsf_canonify(sstate->dotdsf, i);
1148 sstate->looplen[i] = len;
1153 /* Merge two lines because the solver has deduced that they must be either
1154 * identical or opposite. Returns TRUE if this is new information, otherwise
1156 static int merge_lines(solver_state *sstate, int i, int j, int inverse
1158 , const char *reason
1164 assert(i < sstate->state->game_grid->num_edges);
1165 assert(j < sstate->state->game_grid->num_edges);
1167 i = edsf_canonify(sstate->linedsf, i, &inv_tmp);
1169 j = edsf_canonify(sstate->linedsf, j, &inv_tmp);
1172 edsf_merge(sstate->linedsf, i, j, inverse);
1176 fprintf(stderr, "%s [%d] [%d] %s(%s)\n",
1178 inverse ? "inverse " : "", reason);
1185 #define merge_lines(a, b, c, d) \
1186 merge_lines(a, b, c, d, __FUNCTION__)
1189 /* Count the number of lines of a particular type currently going into the
1191 static int dot_order(const game_state* state, int dot, char line_type)
1194 grid *g = state->game_grid;
1195 grid_dot *d = g->dots + dot;
1198 for (i = 0; i < d->order; i++) {
1199 grid_edge *e = d->edges[i];
1200 if (state->lines[e - g->edges] == line_type)
1206 /* Count the number of lines of a particular type currently surrounding the
1208 static int face_order(const game_state* state, int face, char line_type)
1211 grid *g = state->game_grid;
1212 grid_face *f = g->faces + face;
1215 for (i = 0; i < f->order; i++) {
1216 grid_edge *e = f->edges[i];
1217 if (state->lines[e - g->edges] == line_type)
1223 /* Set all lines bordering a dot of type old_type to type new_type
1224 * Return value tells caller whether this function actually did anything */
1225 static int dot_setall(solver_state *sstate, int dot,
1226 char old_type, char new_type)
1228 int retval = FALSE, r;
1229 game_state *state = sstate->state;
1234 if (old_type == new_type)
1237 g = state->game_grid;
1240 for (i = 0; i < d->order; i++) {
1241 int line_index = d->edges[i] - g->edges;
1242 if (state->lines[line_index] == old_type) {
1243 r = solver_set_line(sstate, line_index, new_type);
1251 /* Set all lines bordering a face of type old_type to type new_type */
1252 static int face_setall(solver_state *sstate, int face,
1253 char old_type, char new_type)
1255 int retval = FALSE, r;
1256 game_state *state = sstate->state;
1261 if (old_type == new_type)
1264 g = state->game_grid;
1265 f = g->faces + face;
1267 for (i = 0; i < f->order; i++) {
1268 int line_index = f->edges[i] - g->edges;
1269 if (state->lines[line_index] == old_type) {
1270 r = solver_set_line(sstate, line_index, new_type);
1278 /* ----------------------------------------------------------------------
1279 * Loop generation and clue removal
1282 static void add_full_clues(game_state *state, random_state *rs)
1284 signed char *clues = state->clues;
1285 grid *g = state->game_grid;
1286 char *board = snewn(g->num_faces, char);
1289 generate_loop(g, board, rs, NULL, NULL);
1291 /* Fill out all the clues by initialising to 0, then iterating over
1292 * all edges and incrementing each clue as we find edges that border
1293 * between BLACK/WHITE faces. While we're at it, we verify that the
1294 * algorithm does work, and there aren't any GREY faces still there. */
1295 memset(clues, 0, g->num_faces);
1296 for (i = 0; i < g->num_edges; i++) {
1297 grid_edge *e = g->edges + i;
1298 grid_face *f1 = e->face1;
1299 grid_face *f2 = e->face2;
1300 enum face_colour c1 = FACE_COLOUR(f1);
1301 enum face_colour c2 = FACE_COLOUR(f2);
1302 assert(c1 != FACE_GREY);
1303 assert(c2 != FACE_GREY);
1305 if (f1) clues[f1 - g->faces]++;
1306 if (f2) clues[f2 - g->faces]++;
1313 static int game_has_unique_soln(const game_state *state, int diff)
1316 solver_state *sstate_new;
1317 solver_state *sstate = new_solver_state((game_state *)state, diff);
1319 sstate_new = solve_game_rec(sstate);
1321 assert(sstate_new->solver_status != SOLVER_MISTAKE);
1322 ret = (sstate_new->solver_status == SOLVER_SOLVED);
1324 free_solver_state(sstate_new);
1325 free_solver_state(sstate);
1331 /* Remove clues one at a time at random. */
1332 static game_state *remove_clues(game_state *state, random_state *rs,
1336 int num_faces = state->game_grid->num_faces;
1337 game_state *ret = dup_game(state), *saved_ret;
1340 /* We need to remove some clues. We'll do this by forming a list of all
1341 * available clues, shuffling it, then going along one at a
1342 * time clearing each clue in turn for which doing so doesn't render the
1343 * board unsolvable. */
1344 face_list = snewn(num_faces, int);
1345 for (n = 0; n < num_faces; ++n) {
1349 shuffle(face_list, num_faces, sizeof(int), rs);
1351 for (n = 0; n < num_faces; ++n) {
1352 saved_ret = dup_game(ret);
1353 ret->clues[face_list[n]] = -1;
1355 if (game_has_unique_soln(ret, diff)) {
1356 free_game(saved_ret);
1368 static char *new_game_desc(const game_params *params, random_state *rs,
1369 char **aux, int interactive)
1371 /* solution and description both use run-length encoding in obvious ways */
1372 char *retval, *game_desc, *grid_desc;
1374 game_state *state = snew(game_state);
1375 game_state *state_new;
1377 grid_desc = grid_new_desc(grid_types[params->type], params->w, params->h, rs);
1378 state->game_grid = g = loopy_generate_grid(params, grid_desc);
1380 state->clues = snewn(g->num_faces, signed char);
1381 state->lines = snewn(g->num_edges, char);
1382 state->line_errors = snewn(g->num_edges, unsigned char);
1384 state->grid_type = params->type;
1388 memset(state->lines, LINE_UNKNOWN, g->num_edges);
1389 memset(state->line_errors, 0, g->num_edges);
1391 state->solved = state->cheated = FALSE;
1393 /* Get a new random solvable board with all its clues filled in. Yes, this
1394 * can loop for ever if the params are suitably unfavourable, but
1395 * preventing games smaller than 4x4 seems to stop this happening */
1397 add_full_clues(state, rs);
1398 } while (!game_has_unique_soln(state, params->diff));
1400 state_new = remove_clues(state, rs, params->diff);
1405 if (params->diff > 0 && game_has_unique_soln(state, params->diff-1)) {
1407 fprintf(stderr, "Rejecting board, it is too easy\n");
1409 goto newboard_please;
1412 game_desc = state_to_text(state);
1417 retval = snewn(strlen(grid_desc) + 1 + strlen(game_desc) + 1, char);
1418 sprintf(retval, "%s%c%s", grid_desc, (int)GRID_DESC_SEP, game_desc);
1425 assert(!validate_desc(params, retval));
1430 static game_state *new_game(midend *me, const game_params *params,
1434 game_state *state = snew(game_state);
1435 int empties_to_make = 0;
1440 int num_faces, num_edges;
1442 grid_desc = extract_grid_desc(&desc);
1443 state->game_grid = g = loopy_generate_grid(params, grid_desc);
1444 if (grid_desc) sfree(grid_desc);
1448 num_faces = g->num_faces;
1449 num_edges = g->num_edges;
1451 state->clues = snewn(num_faces, signed char);
1452 state->lines = snewn(num_edges, char);
1453 state->line_errors = snewn(num_edges, unsigned char);
1455 state->solved = state->cheated = FALSE;
1457 state->grid_type = params->type;
1459 for (i = 0; i < num_faces; i++) {
1460 if (empties_to_make) {
1462 state->clues[i] = -1;
1468 n2 = *dp - 'A' + 10;
1469 if (n >= 0 && n < 10) {
1470 state->clues[i] = n;
1471 } else if (n2 >= 10 && n2 < 36) {
1472 state->clues[i] = n2;
1476 state->clues[i] = -1;
1477 empties_to_make = n - 1;
1482 memset(state->lines, LINE_UNKNOWN, num_edges);
1483 memset(state->line_errors, 0, num_edges);
1487 /* Calculates the line_errors data, and checks if the current state is a
1489 static int check_completion(game_state *state)
1491 grid *g = state->game_grid;
1493 int num_faces = g->num_faces;
1495 int infinite_area, finite_area;
1496 int loops_found = 0;
1497 int found_edge_not_in_loop = FALSE;
1499 memset(state->line_errors, 0, g->num_edges);
1501 /* LL implementation of SGT's idea:
1502 * A loop will partition the grid into an inside and an outside.
1503 * If there is more than one loop, the grid will be partitioned into
1504 * even more distinct regions. We can therefore track equivalence of
1505 * faces, by saying that two faces are equivalent when there is a non-YES
1506 * edge between them.
1507 * We could keep track of the number of connected components, by counting
1508 * the number of dsf-merges that aren't no-ops.
1509 * But we're only interested in 3 separate cases:
1510 * no loops, one loop, more than one loop.
1512 * No loops: all faces are equivalent to the infinite face.
1513 * One loop: only two equivalence classes - finite and infinite.
1514 * >= 2 loops: there are 2 distinct finite regions.
1516 * So we simply make two passes through all the edges.
1517 * In the first pass, we dsf-merge the two faces bordering each non-YES
1519 * In the second pass, we look for YES-edges bordering:
1520 * a) two non-equivalent faces.
1521 * b) two non-equivalent faces, and one of them is part of a different
1522 * finite area from the first finite area we've seen.
1524 * An occurrence of a) means there is at least one loop.
1525 * An occurrence of b) means there is more than one loop.
1526 * Edges satisfying a) are marked as errors.
1528 * While we're at it, we set a flag if we find a YES edge that is not
1530 * This information will help decide, if there's a single loop, whether it
1531 * is a candidate for being a solution (that is, all YES edges are part of
1534 * If there is a candidate loop, we then go through all clues and check
1535 * they are all satisfied. If so, we have found a solution and we can
1536 * unmark all line_errors.
1539 /* Infinite face is at the end - its index is num_faces.
1540 * This macro is just to make this obvious! */
1541 #define INF_FACE num_faces
1542 dsf = snewn(num_faces + 1, int);
1543 dsf_init(dsf, num_faces + 1);
1546 for (i = 0; i < g->num_edges; i++) {
1547 grid_edge *e = g->edges + i;
1548 int f1 = e->face1 ? e->face1 - g->faces : INF_FACE;
1549 int f2 = e->face2 ? e->face2 - g->faces : INF_FACE;
1550 if (state->lines[i] != LINE_YES)
1551 dsf_merge(dsf, f1, f2);
1555 infinite_area = dsf_canonify(dsf, INF_FACE);
1557 for (i = 0; i < g->num_edges; i++) {
1558 grid_edge *e = g->edges + i;
1559 int f1 = e->face1 ? e->face1 - g->faces : INF_FACE;
1560 int can1 = dsf_canonify(dsf, f1);
1561 int f2 = e->face2 ? e->face2 - g->faces : INF_FACE;
1562 int can2 = dsf_canonify(dsf, f2);
1563 if (state->lines[i] != LINE_YES) continue;
1566 /* Faces are equivalent, so this edge not part of a loop */
1567 found_edge_not_in_loop = TRUE;
1570 state->line_errors[i] = TRUE;
1571 if (loops_found == 0) loops_found = 1;
1573 /* Don't bother with further checks if we've already found 2 loops */
1574 if (loops_found == 2) continue;
1576 if (finite_area == -1) {
1577 /* Found our first finite area */
1578 if (can1 != infinite_area)
1584 /* Have we found a second area? */
1585 if (finite_area != -1) {
1586 if (can1 != infinite_area && can1 != finite_area) {
1590 if (can2 != infinite_area && can2 != finite_area) {
1597 printf("loops_found = %d\n", loops_found);
1598 printf("found_edge_not_in_loop = %s\n",
1599 found_edge_not_in_loop ? "TRUE" : "FALSE");
1602 sfree(dsf); /* No longer need the dsf */
1604 /* Have we found a candidate loop? */
1605 if (loops_found == 1 && !found_edge_not_in_loop) {
1606 /* Yes, so check all clues are satisfied */
1607 int found_clue_violation = FALSE;
1608 for (i = 0; i < num_faces; i++) {
1609 int c = state->clues[i];
1611 if (face_order(state, i, LINE_YES) != c) {
1612 found_clue_violation = TRUE;
1618 if (!found_clue_violation) {
1619 /* The loop is good */
1620 memset(state->line_errors, 0, g->num_edges);
1621 return TRUE; /* No need to bother checking for dot violations */
1625 /* Check for dot violations */
1626 for (i = 0; i < g->num_dots; i++) {
1627 int yes = dot_order(state, i, LINE_YES);
1628 int unknown = dot_order(state, i, LINE_UNKNOWN);
1629 if ((yes == 1 && unknown == 0) || (yes >= 3)) {
1630 /* violation, so mark all YES edges as errors */
1631 grid_dot *d = g->dots + i;
1633 for (j = 0; j < d->order; j++) {
1634 int e = d->edges[j] - g->edges;
1635 if (state->lines[e] == LINE_YES)
1636 state->line_errors[e] = TRUE;
1643 /* ----------------------------------------------------------------------
1646 * Our solver modes operate as follows. Each mode also uses the modes above it.
1649 * Just implement the rules of the game.
1651 * Normal and Tricky Modes
1652 * For each (adjacent) pair of lines through each dot we store a bit for
1653 * whether at least one of them is on and whether at most one is on. (If we
1654 * know both or neither is on that's already stored more directly.)
1657 * Use edsf data structure to make equivalence classes of lines that are
1658 * known identical to or opposite to one another.
1663 * For general grids, we consider "dlines" to be pairs of lines joined
1664 * at a dot. The lines must be adjacent around the dot, so we can think of
1665 * a dline as being a dot+face combination. Or, a dot+edge combination where
1666 * the second edge is taken to be the next clockwise edge from the dot.
1667 * Original loopy code didn't have this extra restriction of the lines being
1668 * adjacent. From my tests with square grids, this extra restriction seems to
1669 * take little, if anything, away from the quality of the puzzles.
1670 * A dline can be uniquely identified by an edge/dot combination, given that
1671 * a dline-pair always goes clockwise around its common dot. The edge/dot
1672 * combination can be represented by an edge/bool combination - if bool is
1673 * TRUE, use edge->dot1 else use edge->dot2. So the total number of dlines is
1674 * exactly twice the number of edges in the grid - although the dlines
1675 * spanning the infinite face are not all that useful to the solver.
1676 * Note that, by convention, a dline goes clockwise around its common dot,
1677 * which means the dline goes anti-clockwise around its common face.
1680 /* Helper functions for obtaining an index into an array of dlines, given
1681 * various information. We assume the grid layout conventions about how
1682 * the various lists are interleaved - see grid_make_consistent() for
1685 /* i points to the first edge of the dline pair, reading clockwise around
1687 static int dline_index_from_dot(grid *g, grid_dot *d, int i)
1689 grid_edge *e = d->edges[i];
1694 if (i2 == d->order) i2 = 0;
1697 ret = 2 * (e - g->edges) + ((e->dot1 == d) ? 1 : 0);
1699 printf("dline_index_from_dot: d=%d,i=%d, edges [%d,%d] - %d\n",
1700 (int)(d - g->dots), i, (int)(e - g->edges),
1701 (int)(e2 - g->edges), ret);
1705 /* i points to the second edge of the dline pair, reading clockwise around
1706 * the face. That is, the edges of the dline, starting at edge{i}, read
1707 * anti-clockwise around the face. By layout conventions, the common dot
1708 * of the dline will be f->dots[i] */
1709 static int dline_index_from_face(grid *g, grid_face *f, int i)
1711 grid_edge *e = f->edges[i];
1712 grid_dot *d = f->dots[i];
1717 if (i2 < 0) i2 += f->order;
1720 ret = 2 * (e - g->edges) + ((e->dot1 == d) ? 1 : 0);
1722 printf("dline_index_from_face: f=%d,i=%d, edges [%d,%d] - %d\n",
1723 (int)(f - g->faces), i, (int)(e - g->edges),
1724 (int)(e2 - g->edges), ret);
1728 static int is_atleastone(const char *dline_array, int index)
1730 return BIT_SET(dline_array[index], 0);
1732 static int set_atleastone(char *dline_array, int index)
1734 return SET_BIT(dline_array[index], 0);
1736 static int is_atmostone(const char *dline_array, int index)
1738 return BIT_SET(dline_array[index], 1);
1740 static int set_atmostone(char *dline_array, int index)
1742 return SET_BIT(dline_array[index], 1);
1745 static void array_setall(char *array, char from, char to, int len)
1747 char *p = array, *p_old = p;
1748 int len_remaining = len;
1750 while ((p = memchr(p, from, len_remaining))) {
1752 len_remaining -= p - p_old;
1757 /* Helper, called when doing dline dot deductions, in the case where we
1758 * have 4 UNKNOWNs, and two of them (adjacent) have *exactly* one YES between
1759 * them (because of dline atmostone/atleastone).
1760 * On entry, edge points to the first of these two UNKNOWNs. This function
1761 * will find the opposite UNKNOWNS (if they are adjacent to one another)
1762 * and set their corresponding dline to atleastone. (Setting atmostone
1763 * already happens in earlier dline deductions) */
1764 static int dline_set_opp_atleastone(solver_state *sstate,
1765 grid_dot *d, int edge)
1767 game_state *state = sstate->state;
1768 grid *g = state->game_grid;
1771 for (opp = 0; opp < N; opp++) {
1772 int opp_dline_index;
1773 if (opp == edge || opp == edge+1 || opp == edge-1)
1775 if (opp == 0 && edge == N-1)
1777 if (opp == N-1 && edge == 0)
1780 if (opp2 == N) opp2 = 0;
1781 /* Check if opp, opp2 point to LINE_UNKNOWNs */
1782 if (state->lines[d->edges[opp] - g->edges] != LINE_UNKNOWN)
1784 if (state->lines[d->edges[opp2] - g->edges] != LINE_UNKNOWN)
1786 /* Found opposite UNKNOWNS and they're next to each other */
1787 opp_dline_index = dline_index_from_dot(g, d, opp);
1788 return set_atleastone(sstate->dlines, opp_dline_index);
1794 /* Set pairs of lines around this face which are known to be identical, to
1795 * the given line_state */
1796 static int face_setall_identical(solver_state *sstate, int face_index,
1797 enum line_state line_new)
1799 /* can[dir] contains the canonical line associated with the line in
1800 * direction dir from the square in question. Similarly inv[dir] is
1801 * whether or not the line in question is inverse to its canonical
1804 game_state *state = sstate->state;
1805 grid *g = state->game_grid;
1806 grid_face *f = g->faces + face_index;
1809 int can1, can2, inv1, inv2;
1811 for (i = 0; i < N; i++) {
1812 int line1_index = f->edges[i] - g->edges;
1813 if (state->lines[line1_index] != LINE_UNKNOWN)
1815 for (j = i + 1; j < N; j++) {
1816 int line2_index = f->edges[j] - g->edges;
1817 if (state->lines[line2_index] != LINE_UNKNOWN)
1820 /* Found two UNKNOWNS */
1821 can1 = edsf_canonify(sstate->linedsf, line1_index, &inv1);
1822 can2 = edsf_canonify(sstate->linedsf, line2_index, &inv2);
1823 if (can1 == can2 && inv1 == inv2) {
1824 solver_set_line(sstate, line1_index, line_new);
1825 solver_set_line(sstate, line2_index, line_new);
1832 /* Given a dot or face, and a count of LINE_UNKNOWNs, find them and
1833 * return the edge indices into e. */
1834 static void find_unknowns(game_state *state,
1835 grid_edge **edge_list, /* Edge list to search (from a face or a dot) */
1836 int expected_count, /* Number of UNKNOWNs (comes from solver's cache) */
1837 int *e /* Returned edge indices */)
1840 grid *g = state->game_grid;
1841 while (c < expected_count) {
1842 int line_index = *edge_list - g->edges;
1843 if (state->lines[line_index] == LINE_UNKNOWN) {
1851 /* If we have a list of edges, and we know whether the number of YESs should
1852 * be odd or even, and there are only a few UNKNOWNs, we can do some simple
1853 * linedsf deductions. This can be used for both face and dot deductions.
1854 * Returns the difficulty level of the next solver that should be used,
1855 * or DIFF_MAX if no progress was made. */
1856 static int parity_deductions(solver_state *sstate,
1857 grid_edge **edge_list, /* Edge list (from a face or a dot) */
1858 int total_parity, /* Expected number of YESs modulo 2 (either 0 or 1) */
1861 game_state *state = sstate->state;
1862 int diff = DIFF_MAX;
1863 int *linedsf = sstate->linedsf;
1865 if (unknown_count == 2) {
1866 /* Lines are known alike/opposite, depending on inv. */
1868 find_unknowns(state, edge_list, 2, e);
1869 if (merge_lines(sstate, e[0], e[1], total_parity))
1870 diff = min(diff, DIFF_HARD);
1871 } else if (unknown_count == 3) {
1873 int can[3]; /* canonical edges */
1874 int inv[3]; /* whether can[x] is inverse to e[x] */
1875 find_unknowns(state, edge_list, 3, e);
1876 can[0] = edsf_canonify(linedsf, e[0], inv);
1877 can[1] = edsf_canonify(linedsf, e[1], inv+1);
1878 can[2] = edsf_canonify(linedsf, e[2], inv+2);
1879 if (can[0] == can[1]) {
1880 if (solver_set_line(sstate, e[2], (total_parity^inv[0]^inv[1]) ?
1881 LINE_YES : LINE_NO))
1882 diff = min(diff, DIFF_EASY);
1884 if (can[0] == can[2]) {
1885 if (solver_set_line(sstate, e[1], (total_parity^inv[0]^inv[2]) ?
1886 LINE_YES : LINE_NO))
1887 diff = min(diff, DIFF_EASY);
1889 if (can[1] == can[2]) {
1890 if (solver_set_line(sstate, e[0], (total_parity^inv[1]^inv[2]) ?
1891 LINE_YES : LINE_NO))
1892 diff = min(diff, DIFF_EASY);
1894 } else if (unknown_count == 4) {
1896 int can[4]; /* canonical edges */
1897 int inv[4]; /* whether can[x] is inverse to e[x] */
1898 find_unknowns(state, edge_list, 4, e);
1899 can[0] = edsf_canonify(linedsf, e[0], inv);
1900 can[1] = edsf_canonify(linedsf, e[1], inv+1);
1901 can[2] = edsf_canonify(linedsf, e[2], inv+2);
1902 can[3] = edsf_canonify(linedsf, e[3], inv+3);
1903 if (can[0] == can[1]) {
1904 if (merge_lines(sstate, e[2], e[3], total_parity^inv[0]^inv[1]))
1905 diff = min(diff, DIFF_HARD);
1906 } else if (can[0] == can[2]) {
1907 if (merge_lines(sstate, e[1], e[3], total_parity^inv[0]^inv[2]))
1908 diff = min(diff, DIFF_HARD);
1909 } else if (can[0] == can[3]) {
1910 if (merge_lines(sstate, e[1], e[2], total_parity^inv[0]^inv[3]))
1911 diff = min(diff, DIFF_HARD);
1912 } else if (can[1] == can[2]) {
1913 if (merge_lines(sstate, e[0], e[3], total_parity^inv[1]^inv[2]))
1914 diff = min(diff, DIFF_HARD);
1915 } else if (can[1] == can[3]) {
1916 if (merge_lines(sstate, e[0], e[2], total_parity^inv[1]^inv[3]))
1917 diff = min(diff, DIFF_HARD);
1918 } else if (can[2] == can[3]) {
1919 if (merge_lines(sstate, e[0], e[1], total_parity^inv[2]^inv[3]))
1920 diff = min(diff, DIFF_HARD);
1928 * These are the main solver functions.
1930 * Their return values are diff values corresponding to the lowest mode solver
1931 * that would notice the work that they have done. For example if the normal
1932 * mode solver adds actual lines or crosses, it will return DIFF_EASY as the
1933 * easy mode solver might be able to make progress using that. It doesn't make
1934 * sense for one of them to return a diff value higher than that of the
1937 * Each function returns the lowest value it can, as early as possible, in
1938 * order to try and pass as much work as possible back to the lower level
1939 * solvers which progress more quickly.
1942 /* PROPOSED NEW DESIGN:
1943 * We have a work queue consisting of 'events' notifying us that something has
1944 * happened that a particular solver mode might be interested in. For example
1945 * the hard mode solver might do something that helps the normal mode solver at
1946 * dot [x,y] in which case it will enqueue an event recording this fact. Then
1947 * we pull events off the work queue, and hand each in turn to the solver that
1948 * is interested in them. If a solver reports that it failed we pass the same
1949 * event on to progressively more advanced solvers and the loop detector. Once
1950 * we've exhausted an event, or it has helped us progress, we drop it and
1951 * continue to the next one. The events are sorted first in order of solver
1952 * complexity (easy first) then order of insertion (oldest first).
1953 * Once we run out of events we loop over each permitted solver in turn
1954 * (easiest first) until either a deduction is made (and an event therefore
1955 * emerges) or no further deductions can be made (in which case we've failed).
1958 * * How do we 'loop over' a solver when both dots and squares are concerned.
1959 * Answer: first all squares then all dots.
1962 static int trivial_deductions(solver_state *sstate)
1964 int i, current_yes, current_no;
1965 game_state *state = sstate->state;
1966 grid *g = state->game_grid;
1967 int diff = DIFF_MAX;
1969 /* Per-face deductions */
1970 for (i = 0; i < g->num_faces; i++) {
1971 grid_face *f = g->faces + i;
1973 if (sstate->face_solved[i])
1976 current_yes = sstate->face_yes_count[i];
1977 current_no = sstate->face_no_count[i];
1979 if (current_yes + current_no == f->order) {
1980 sstate->face_solved[i] = TRUE;
1984 if (state->clues[i] < 0)
1988 * This code checks whether the numeric clue on a face is so
1989 * large as to permit all its remaining LINE_UNKNOWNs to be
1990 * filled in as LINE_YES, or alternatively so small as to
1991 * permit them all to be filled in as LINE_NO.
1994 if (state->clues[i] < current_yes) {
1995 sstate->solver_status = SOLVER_MISTAKE;
1998 if (state->clues[i] == current_yes) {
1999 if (face_setall(sstate, i, LINE_UNKNOWN, LINE_NO))
2000 diff = min(diff, DIFF_EASY);
2001 sstate->face_solved[i] = TRUE;
2005 if (f->order - state->clues[i] < current_no) {
2006 sstate->solver_status = SOLVER_MISTAKE;
2009 if (f->order - state->clues[i] == current_no) {
2010 if (face_setall(sstate, i, LINE_UNKNOWN, LINE_YES))
2011 diff = min(diff, DIFF_EASY);
2012 sstate->face_solved[i] = TRUE;
2016 if (f->order - state->clues[i] == current_no + 1 &&
2017 f->order - current_yes - current_no > 2) {
2019 * One small refinement to the above: we also look for any
2020 * adjacent pair of LINE_UNKNOWNs around the face with
2021 * some LINE_YES incident on it from elsewhere. If we find
2022 * one, then we know that pair of LINE_UNKNOWNs can't
2023 * _both_ be LINE_YES, and hence that pushes us one line
2024 * closer to being able to determine all the rest.
2026 int j, k, e1, e2, e, d;
2028 for (j = 0; j < f->order; j++) {
2029 e1 = f->edges[j] - g->edges;
2030 e2 = f->edges[j+1 < f->order ? j+1 : 0] - g->edges;
2032 if (g->edges[e1].dot1 == g->edges[e2].dot1 ||
2033 g->edges[e1].dot1 == g->edges[e2].dot2) {
2034 d = g->edges[e1].dot1 - g->dots;
2036 assert(g->edges[e1].dot2 == g->edges[e2].dot1 ||
2037 g->edges[e1].dot2 == g->edges[e2].dot2);
2038 d = g->edges[e1].dot2 - g->dots;
2041 if (state->lines[e1] == LINE_UNKNOWN &&
2042 state->lines[e2] == LINE_UNKNOWN) {
2043 for (k = 0; k < g->dots[d].order; k++) {
2044 int e = g->dots[d].edges[k] - g->edges;
2045 if (state->lines[e] == LINE_YES)
2046 goto found; /* multi-level break */
2054 * If we get here, we've found such a pair of edges, and
2055 * they're e1 and e2.
2057 for (j = 0; j < f->order; j++) {
2058 e = f->edges[j] - g->edges;
2059 if (state->lines[e] == LINE_UNKNOWN && e != e1 && e != e2) {
2060 int r = solver_set_line(sstate, e, LINE_YES);
2062 diff = min(diff, DIFF_EASY);
2068 check_caches(sstate);
2070 /* Per-dot deductions */
2071 for (i = 0; i < g->num_dots; i++) {
2072 grid_dot *d = g->dots + i;
2073 int yes, no, unknown;
2075 if (sstate->dot_solved[i])
2078 yes = sstate->dot_yes_count[i];
2079 no = sstate->dot_no_count[i];
2080 unknown = d->order - yes - no;
2084 sstate->dot_solved[i] = TRUE;
2085 } else if (unknown == 1) {
2086 dot_setall(sstate, i, LINE_UNKNOWN, LINE_NO);
2087 diff = min(diff, DIFF_EASY);
2088 sstate->dot_solved[i] = TRUE;
2090 } else if (yes == 1) {
2092 sstate->solver_status = SOLVER_MISTAKE;
2094 } else if (unknown == 1) {
2095 dot_setall(sstate, i, LINE_UNKNOWN, LINE_YES);
2096 diff = min(diff, DIFF_EASY);
2098 } else if (yes == 2) {
2100 dot_setall(sstate, i, LINE_UNKNOWN, LINE_NO);
2101 diff = min(diff, DIFF_EASY);
2103 sstate->dot_solved[i] = TRUE;
2105 sstate->solver_status = SOLVER_MISTAKE;
2110 check_caches(sstate);
2115 static int dline_deductions(solver_state *sstate)
2117 game_state *state = sstate->state;
2118 grid *g = state->game_grid;
2119 char *dlines = sstate->dlines;
2121 int diff = DIFF_MAX;
2123 /* ------ Face deductions ------ */
2125 /* Given a set of dline atmostone/atleastone constraints, need to figure
2126 * out if we can deduce any further info. For more general faces than
2127 * squares, this turns out to be a tricky problem.
2128 * The approach taken here is to define (per face) NxN matrices:
2129 * "maxs" and "mins".
2130 * The entries maxs(j,k) and mins(j,k) define the upper and lower limits
2131 * for the possible number of edges that are YES between positions j and k
2132 * going clockwise around the face. Can think of j and k as marking dots
2133 * around the face (recall the labelling scheme: edge0 joins dot0 to dot1,
2134 * edge1 joins dot1 to dot2 etc).
2135 * Trivially, mins(j,j) = maxs(j,j) = 0, and we don't even bother storing
2136 * these. mins(j,j+1) and maxs(j,j+1) are determined by whether edge{j}
2137 * is YES, NO or UNKNOWN. mins(j,j+2) and maxs(j,j+2) are related to
2138 * the dline atmostone/atleastone status for edges j and j+1.
2140 * Then we calculate the remaining entries recursively. We definitely
2142 * mins(j,k) >= { mins(j,u) + mins(u,k) } for any u between j and k.
2143 * This is because any valid placement of YESs between j and k must give
2144 * a valid placement between j and u, and also between u and k.
2145 * I believe it's sufficient to use just the two values of u:
2146 * j+1 and j+2. Seems to work well in practice - the bounds we compute
2147 * are rigorous, even if they might not be best-possible.
2149 * Once we have maxs and mins calculated, we can make inferences about
2150 * each dline{j,j+1} by looking at the possible complementary edge-counts
2151 * mins(j+2,j) and maxs(j+2,j) and comparing these with the face clue.
2152 * As well as dlines, we can make similar inferences about single edges.
2153 * For example, consider a pentagon with clue 3, and we know at most one
2154 * of (edge0, edge1) is YES, and at most one of (edge2, edge3) is YES.
2155 * We could then deduce edge4 is YES, because maxs(0,4) would be 2, so
2156 * that final edge would have to be YES to make the count up to 3.
2159 /* Much quicker to allocate arrays on the stack than the heap, so
2160 * define the largest possible face size, and base our array allocations
2161 * on that. We check this with an assertion, in case someone decides to
2162 * make a grid which has larger faces than this. Note, this algorithm
2163 * could get quite expensive if there are many large faces. */
2164 #define MAX_FACE_SIZE 12
2166 for (i = 0; i < g->num_faces; i++) {
2167 int maxs[MAX_FACE_SIZE][MAX_FACE_SIZE];
2168 int mins[MAX_FACE_SIZE][MAX_FACE_SIZE];
2169 grid_face *f = g->faces + i;
2172 int clue = state->clues[i];
2173 assert(N <= MAX_FACE_SIZE);
2174 if (sstate->face_solved[i])
2176 if (clue < 0) continue;
2178 /* Calculate the (j,j+1) entries */
2179 for (j = 0; j < N; j++) {
2180 int edge_index = f->edges[j] - g->edges;
2182 enum line_state line1 = state->lines[edge_index];
2183 enum line_state line2;
2187 maxs[j][k] = (line1 == LINE_NO) ? 0 : 1;
2188 mins[j][k] = (line1 == LINE_YES) ? 1 : 0;
2189 /* Calculate the (j,j+2) entries */
2190 dline_index = dline_index_from_face(g, f, k);
2191 edge_index = f->edges[k] - g->edges;
2192 line2 = state->lines[edge_index];
2198 if (line1 == LINE_NO) tmp--;
2199 if (line2 == LINE_NO) tmp--;
2200 if (tmp == 2 && is_atmostone(dlines, dline_index))
2206 if (line1 == LINE_YES) tmp++;
2207 if (line2 == LINE_YES) tmp++;
2208 if (tmp == 0 && is_atleastone(dlines, dline_index))
2213 /* Calculate the (j,j+m) entries for m between 3 and N-1 */
2214 for (m = 3; m < N; m++) {
2215 for (j = 0; j < N; j++) {
2223 maxs[j][k] = maxs[j][u] + maxs[u][k];
2224 mins[j][k] = mins[j][u] + mins[u][k];
2225 tmp = maxs[j][v] + maxs[v][k];
2226 maxs[j][k] = min(maxs[j][k], tmp);
2227 tmp = mins[j][v] + mins[v][k];
2228 mins[j][k] = max(mins[j][k], tmp);
2232 /* See if we can make any deductions */
2233 for (j = 0; j < N; j++) {
2235 grid_edge *e = f->edges[j];
2236 int line_index = e - g->edges;
2239 if (state->lines[line_index] != LINE_UNKNOWN)
2244 /* minimum YESs in the complement of this edge */
2245 if (mins[k][j] > clue) {
2246 sstate->solver_status = SOLVER_MISTAKE;
2249 if (mins[k][j] == clue) {
2250 /* setting this edge to YES would make at least
2251 * (clue+1) edges - contradiction */
2252 solver_set_line(sstate, line_index, LINE_NO);
2253 diff = min(diff, DIFF_EASY);
2255 if (maxs[k][j] < clue - 1) {
2256 sstate->solver_status = SOLVER_MISTAKE;
2259 if (maxs[k][j] == clue - 1) {
2260 /* Only way to satisfy the clue is to set edge{j} as YES */
2261 solver_set_line(sstate, line_index, LINE_YES);
2262 diff = min(diff, DIFF_EASY);
2265 /* More advanced deduction that allows propagation along diagonal
2266 * chains of faces connected by dots, for example, 3-2-...-2-3
2267 * in square grids. */
2268 if (sstate->diff >= DIFF_TRICKY) {
2269 /* Now see if we can make dline deduction for edges{j,j+1} */
2271 if (state->lines[e - g->edges] != LINE_UNKNOWN)
2272 /* Only worth doing this for an UNKNOWN,UNKNOWN pair.
2273 * Dlines where one of the edges is known, are handled in the
2277 dline_index = dline_index_from_face(g, f, k);
2281 /* minimum YESs in the complement of this dline */
2282 if (mins[k][j] > clue - 2) {
2283 /* Adding 2 YESs would break the clue */
2284 if (set_atmostone(dlines, dline_index))
2285 diff = min(diff, DIFF_NORMAL);
2287 /* maximum YESs in the complement of this dline */
2288 if (maxs[k][j] < clue) {
2289 /* Adding 2 NOs would mean not enough YESs */
2290 if (set_atleastone(dlines, dline_index))
2291 diff = min(diff, DIFF_NORMAL);
2297 if (diff < DIFF_NORMAL)
2300 /* ------ Dot deductions ------ */
2302 for (i = 0; i < g->num_dots; i++) {
2303 grid_dot *d = g->dots + i;
2305 int yes, no, unknown;
2307 if (sstate->dot_solved[i])
2309 yes = sstate->dot_yes_count[i];
2310 no = sstate->dot_no_count[i];
2311 unknown = N - yes - no;
2313 for (j = 0; j < N; j++) {
2316 int line1_index, line2_index;
2317 enum line_state line1, line2;
2320 dline_index = dline_index_from_dot(g, d, j);
2321 line1_index = d->edges[j] - g->edges;
2322 line2_index = d->edges[k] - g->edges;
2323 line1 = state->lines[line1_index];
2324 line2 = state->lines[line2_index];
2326 /* Infer dline state from line state */
2327 if (line1 == LINE_NO || line2 == LINE_NO) {
2328 if (set_atmostone(dlines, dline_index))
2329 diff = min(diff, DIFF_NORMAL);
2331 if (line1 == LINE_YES || line2 == LINE_YES) {
2332 if (set_atleastone(dlines, dline_index))
2333 diff = min(diff, DIFF_NORMAL);
2335 /* Infer line state from dline state */
2336 if (is_atmostone(dlines, dline_index)) {
2337 if (line1 == LINE_YES && line2 == LINE_UNKNOWN) {
2338 solver_set_line(sstate, line2_index, LINE_NO);
2339 diff = min(diff, DIFF_EASY);
2341 if (line2 == LINE_YES && line1 == LINE_UNKNOWN) {
2342 solver_set_line(sstate, line1_index, LINE_NO);
2343 diff = min(diff, DIFF_EASY);
2346 if (is_atleastone(dlines, dline_index)) {
2347 if (line1 == LINE_NO && line2 == LINE_UNKNOWN) {
2348 solver_set_line(sstate, line2_index, LINE_YES);
2349 diff = min(diff, DIFF_EASY);
2351 if (line2 == LINE_NO && line1 == LINE_UNKNOWN) {
2352 solver_set_line(sstate, line1_index, LINE_YES);
2353 diff = min(diff, DIFF_EASY);
2356 /* Deductions that depend on the numbers of lines.
2357 * Only bother if both lines are UNKNOWN, otherwise the
2358 * easy-mode solver (or deductions above) would have taken
2360 if (line1 != LINE_UNKNOWN || line2 != LINE_UNKNOWN)
2363 if (yes == 0 && unknown == 2) {
2364 /* Both these unknowns must be identical. If we know
2365 * atmostone or atleastone, we can make progress. */
2366 if (is_atmostone(dlines, dline_index)) {
2367 solver_set_line(sstate, line1_index, LINE_NO);
2368 solver_set_line(sstate, line2_index, LINE_NO);
2369 diff = min(diff, DIFF_EASY);
2371 if (is_atleastone(dlines, dline_index)) {
2372 solver_set_line(sstate, line1_index, LINE_YES);
2373 solver_set_line(sstate, line2_index, LINE_YES);
2374 diff = min(diff, DIFF_EASY);
2378 if (set_atmostone(dlines, dline_index))
2379 diff = min(diff, DIFF_NORMAL);
2381 if (set_atleastone(dlines, dline_index))
2382 diff = min(diff, DIFF_NORMAL);
2386 /* More advanced deduction that allows propagation along diagonal
2387 * chains of faces connected by dots, for example: 3-2-...-2-3
2388 * in square grids. */
2389 if (sstate->diff >= DIFF_TRICKY) {
2390 /* If we have atleastone set for this dline, infer
2391 * atmostone for each "opposite" dline (that is, each
2392 * dline without edges in common with this one).
2393 * Again, this test is only worth doing if both these
2394 * lines are UNKNOWN. For if one of these lines were YES,
2395 * the (yes == 1) test above would kick in instead. */
2396 if (is_atleastone(dlines, dline_index)) {
2398 for (opp = 0; opp < N; opp++) {
2399 int opp_dline_index;
2400 if (opp == j || opp == j+1 || opp == j-1)
2402 if (j == 0 && opp == N-1)
2404 if (j == N-1 && opp == 0)
2406 opp_dline_index = dline_index_from_dot(g, d, opp);
2407 if (set_atmostone(dlines, opp_dline_index))
2408 diff = min(diff, DIFF_NORMAL);
2410 if (yes == 0 && is_atmostone(dlines, dline_index)) {
2411 /* This dline has *exactly* one YES and there are no
2412 * other YESs. This allows more deductions. */
2414 /* Third unknown must be YES */
2415 for (opp = 0; opp < N; opp++) {
2417 if (opp == j || opp == k)
2419 opp_index = d->edges[opp] - g->edges;
2420 if (state->lines[opp_index] == LINE_UNKNOWN) {
2421 solver_set_line(sstate, opp_index,
2423 diff = min(diff, DIFF_EASY);
2426 } else if (unknown == 4) {
2427 /* Exactly one of opposite UNKNOWNS is YES. We've
2428 * already set atmostone, so set atleastone as
2431 if (dline_set_opp_atleastone(sstate, d, j))
2432 diff = min(diff, DIFF_NORMAL);
2442 static int linedsf_deductions(solver_state *sstate)
2444 game_state *state = sstate->state;
2445 grid *g = state->game_grid;
2446 char *dlines = sstate->dlines;
2448 int diff = DIFF_MAX;
2451 /* ------ Face deductions ------ */
2453 /* A fully-general linedsf deduction seems overly complicated
2454 * (I suspect the problem is NP-complete, though in practice it might just
2455 * be doable because faces are limited in size).
2456 * For simplicity, we only consider *pairs* of LINE_UNKNOWNS that are
2457 * known to be identical. If setting them both to YES (or NO) would break
2458 * the clue, set them to NO (or YES). */
2460 for (i = 0; i < g->num_faces; i++) {
2461 int N, yes, no, unknown;
2464 if (sstate->face_solved[i])
2466 clue = state->clues[i];
2470 N = g->faces[i].order;
2471 yes = sstate->face_yes_count[i];
2472 if (yes + 1 == clue) {
2473 if (face_setall_identical(sstate, i, LINE_NO))
2474 diff = min(diff, DIFF_EASY);
2476 no = sstate->face_no_count[i];
2477 if (no + 1 == N - clue) {
2478 if (face_setall_identical(sstate, i, LINE_YES))
2479 diff = min(diff, DIFF_EASY);
2482 /* Reload YES count, it might have changed */
2483 yes = sstate->face_yes_count[i];
2484 unknown = N - no - yes;
2486 /* Deductions with small number of LINE_UNKNOWNs, based on overall
2487 * parity of lines. */
2488 diff_tmp = parity_deductions(sstate, g->faces[i].edges,
2489 (clue - yes) % 2, unknown);
2490 diff = min(diff, diff_tmp);
2493 /* ------ Dot deductions ------ */
2494 for (i = 0; i < g->num_dots; i++) {
2495 grid_dot *d = g->dots + i;
2498 int yes, no, unknown;
2499 /* Go through dlines, and do any dline<->linedsf deductions wherever
2500 * we find two UNKNOWNS. */
2501 for (j = 0; j < N; j++) {
2502 int dline_index = dline_index_from_dot(g, d, j);
2505 int can1, can2, inv1, inv2;
2507 line1_index = d->edges[j] - g->edges;
2508 if (state->lines[line1_index] != LINE_UNKNOWN)
2511 if (j2 == N) j2 = 0;
2512 line2_index = d->edges[j2] - g->edges;
2513 if (state->lines[line2_index] != LINE_UNKNOWN)
2515 /* Infer dline flags from linedsf */
2516 can1 = edsf_canonify(sstate->linedsf, line1_index, &inv1);
2517 can2 = edsf_canonify(sstate->linedsf, line2_index, &inv2);
2518 if (can1 == can2 && inv1 != inv2) {
2519 /* These are opposites, so set dline atmostone/atleastone */
2520 if (set_atmostone(dlines, dline_index))
2521 diff = min(diff, DIFF_NORMAL);
2522 if (set_atleastone(dlines, dline_index))
2523 diff = min(diff, DIFF_NORMAL);
2526 /* Infer linedsf from dline flags */
2527 if (is_atmostone(dlines, dline_index)
2528 && is_atleastone(dlines, dline_index)) {
2529 if (merge_lines(sstate, line1_index, line2_index, 1))
2530 diff = min(diff, DIFF_HARD);
2534 /* Deductions with small number of LINE_UNKNOWNs, based on overall
2535 * parity of lines. */
2536 yes = sstate->dot_yes_count[i];
2537 no = sstate->dot_no_count[i];
2538 unknown = N - yes - no;
2539 diff_tmp = parity_deductions(sstate, d->edges,
2541 diff = min(diff, diff_tmp);
2544 /* ------ Edge dsf deductions ------ */
2546 /* If the state of a line is known, deduce the state of its canonical line
2547 * too, and vice versa. */
2548 for (i = 0; i < g->num_edges; i++) {
2551 can = edsf_canonify(sstate->linedsf, i, &inv);
2554 s = sstate->state->lines[can];
2555 if (s != LINE_UNKNOWN) {
2556 if (solver_set_line(sstate, i, inv ? OPP(s) : s))
2557 diff = min(diff, DIFF_EASY);
2559 s = sstate->state->lines[i];
2560 if (s != LINE_UNKNOWN) {
2561 if (solver_set_line(sstate, can, inv ? OPP(s) : s))
2562 diff = min(diff, DIFF_EASY);
2570 static int loop_deductions(solver_state *sstate)
2572 int edgecount = 0, clues = 0, satclues = 0, sm1clues = 0;
2573 game_state *state = sstate->state;
2574 grid *g = state->game_grid;
2575 int shortest_chainlen = g->num_dots;
2576 int loop_found = FALSE;
2578 int progress = FALSE;
2582 * Go through the grid and update for all the new edges.
2583 * Since merge_dots() is idempotent, the simplest way to
2584 * do this is just to update for _all_ the edges.
2585 * Also, while we're here, we count the edges.
2587 for (i = 0; i < g->num_edges; i++) {
2588 if (state->lines[i] == LINE_YES) {
2589 loop_found |= merge_dots(sstate, i);
2595 * Count the clues, count the satisfied clues, and count the
2596 * satisfied-minus-one clues.
2598 for (i = 0; i < g->num_faces; i++) {
2599 int c = state->clues[i];
2601 int o = sstate->face_yes_count[i];
2610 for (i = 0; i < g->num_dots; ++i) {
2612 sstate->looplen[dsf_canonify(sstate->dotdsf, i)];
2613 if (dots_connected > 1)
2614 shortest_chainlen = min(shortest_chainlen, dots_connected);
2617 assert(sstate->solver_status == SOLVER_INCOMPLETE);
2619 if (satclues == clues && shortest_chainlen == edgecount) {
2620 sstate->solver_status = SOLVER_SOLVED;
2621 /* This discovery clearly counts as progress, even if we haven't
2622 * just added any lines or anything */
2624 goto finished_loop_deductionsing;
2628 * Now go through looking for LINE_UNKNOWN edges which
2629 * connect two dots that are already in the same
2630 * equivalence class. If we find one, test to see if the
2631 * loop it would create is a solution.
2633 for (i = 0; i < g->num_edges; i++) {
2634 grid_edge *e = g->edges + i;
2635 int d1 = e->dot1 - g->dots;
2636 int d2 = e->dot2 - g->dots;
2638 if (state->lines[i] != LINE_UNKNOWN)
2641 eqclass = dsf_canonify(sstate->dotdsf, d1);
2642 if (eqclass != dsf_canonify(sstate->dotdsf, d2))
2645 val = LINE_NO; /* loop is bad until proven otherwise */
2648 * This edge would form a loop. Next
2649 * question: how long would the loop be?
2650 * Would it equal the total number of edges
2651 * (plus the one we'd be adding if we added
2654 if (sstate->looplen[eqclass] == edgecount + 1) {
2658 * This edge would form a loop which
2659 * took in all the edges in the entire
2660 * grid. So now we need to work out
2661 * whether it would be a valid solution
2662 * to the puzzle, which means we have to
2663 * check if it satisfies all the clues.
2664 * This means that every clue must be
2665 * either satisfied or satisfied-minus-
2666 * 1, and also that the number of
2667 * satisfied-minus-1 clues must be at
2668 * most two and they must lie on either
2669 * side of this edge.
2673 int f = e->face1 - g->faces;
2674 int c = state->clues[f];
2675 if (c >= 0 && sstate->face_yes_count[f] == c - 1)
2679 int f = e->face2 - g->faces;
2680 int c = state->clues[f];
2681 if (c >= 0 && sstate->face_yes_count[f] == c - 1)
2684 if (sm1clues == sm1_nearby &&
2685 sm1clues + satclues == clues) {
2686 val = LINE_YES; /* loop is good! */
2691 * Right. Now we know that adding this edge
2692 * would form a loop, and we know whether
2693 * that loop would be a viable solution or
2696 * If adding this edge produces a solution,
2697 * then we know we've found _a_ solution but
2698 * we don't know that it's _the_ solution -
2699 * if it were provably the solution then
2700 * we'd have deduced this edge some time ago
2701 * without the need to do loop detection. So
2702 * in this state we return SOLVER_AMBIGUOUS,
2703 * which has the effect that hitting Solve
2704 * on a user-provided puzzle will fill in a
2705 * solution but using the solver to
2706 * construct new puzzles won't consider this
2707 * a reasonable deduction for the user to
2710 progress = solver_set_line(sstate, i, val);
2711 assert(progress == TRUE);
2712 if (val == LINE_YES) {
2713 sstate->solver_status = SOLVER_AMBIGUOUS;
2714 goto finished_loop_deductionsing;
2718 finished_loop_deductionsing:
2719 return progress ? DIFF_EASY : DIFF_MAX;
2722 /* This will return a dynamically allocated solver_state containing the (more)
2724 static solver_state *solve_game_rec(const solver_state *sstate_start)
2726 solver_state *sstate;
2728 /* Index of the solver we should call next. */
2731 /* As a speed-optimisation, we avoid re-running solvers that we know
2732 * won't make any progress. This happens when a high-difficulty
2733 * solver makes a deduction that can only help other high-difficulty
2735 * For example: if a new 'dline' flag is set by dline_deductions, the
2736 * trivial_deductions solver cannot do anything with this information.
2737 * If we've already run the trivial_deductions solver (because it's
2738 * earlier in the list), there's no point running it again.
2740 * Therefore: if a solver is earlier in the list than "threshold_index",
2741 * we don't bother running it if it's difficulty level is less than
2744 int threshold_diff = 0;
2745 int threshold_index = 0;
2747 sstate = dup_solver_state(sstate_start);
2749 check_caches(sstate);
2751 while (i < NUM_SOLVERS) {
2752 if (sstate->solver_status == SOLVER_MISTAKE)
2754 if (sstate->solver_status == SOLVER_SOLVED ||
2755 sstate->solver_status == SOLVER_AMBIGUOUS) {
2756 /* solver finished */
2760 if ((solver_diffs[i] >= threshold_diff || i >= threshold_index)
2761 && solver_diffs[i] <= sstate->diff) {
2762 /* current_solver is eligible, so use it */
2763 int next_diff = solver_fns[i](sstate);
2764 if (next_diff != DIFF_MAX) {
2765 /* solver made progress, so use new thresholds and
2766 * start again at top of list. */
2767 threshold_diff = next_diff;
2768 threshold_index = i;
2773 /* current_solver is ineligible, or failed to make progress, so
2774 * go to the next solver in the list */
2778 if (sstate->solver_status == SOLVER_SOLVED ||
2779 sstate->solver_status == SOLVER_AMBIGUOUS) {
2780 /* s/LINE_UNKNOWN/LINE_NO/g */
2781 array_setall(sstate->state->lines, LINE_UNKNOWN, LINE_NO,
2782 sstate->state->game_grid->num_edges);
2789 static char *solve_game(const game_state *state, const game_state *currstate,
2790 const char *aux, char **error)
2793 solver_state *sstate, *new_sstate;
2795 sstate = new_solver_state(state, DIFF_MAX);
2796 new_sstate = solve_game_rec(sstate);
2798 if (new_sstate->solver_status == SOLVER_SOLVED) {
2799 soln = encode_solve_move(new_sstate->state);
2800 } else if (new_sstate->solver_status == SOLVER_AMBIGUOUS) {
2801 soln = encode_solve_move(new_sstate->state);
2802 /**error = "Solver found ambiguous solutions"; */
2804 soln = encode_solve_move(new_sstate->state);
2805 /**error = "Solver failed"; */
2808 free_solver_state(new_sstate);
2809 free_solver_state(sstate);
2814 /* ----------------------------------------------------------------------
2815 * Drawing and mouse-handling
2818 static char *interpret_move(const game_state *state, game_ui *ui,
2819 const game_drawstate *ds,
2820 int x, int y, int button)
2822 grid *g = state->game_grid;
2826 char button_char = ' ';
2827 enum line_state old_state;
2829 button &= ~MOD_MASK;
2831 /* Convert mouse-click (x,y) to grid coordinates */
2832 x -= BORDER(ds->tilesize);
2833 y -= BORDER(ds->tilesize);
2834 x = x * g->tilesize / ds->tilesize;
2835 y = y * g->tilesize / ds->tilesize;
2839 e = grid_nearest_edge(g, x, y);
2845 /* I think it's only possible to play this game with mouse clicks, sorry */
2846 /* Maybe will add mouse drag support some time */
2847 old_state = state->lines[i];
2851 switch (old_state) {
2869 switch (old_state) {
2888 sprintf(buf, "%d%c", i, (int)button_char);
2894 static game_state *execute_move(const game_state *state, const char *move)
2897 game_state *newstate = dup_game(state);
2899 if (move[0] == 'S') {
2901 newstate->cheated = TRUE;
2906 if (i < 0 || i >= newstate->game_grid->num_edges)
2908 move += strspn(move, "1234567890");
2909 switch (*(move++)) {
2911 newstate->lines[i] = LINE_YES;
2914 newstate->lines[i] = LINE_NO;
2917 newstate->lines[i] = LINE_UNKNOWN;
2925 * Check for completion.
2927 if (check_completion(newstate))
2928 newstate->solved = TRUE;
2933 free_game(newstate);
2937 /* ----------------------------------------------------------------------
2941 /* Convert from grid coordinates to screen coordinates */
2942 static void grid_to_screen(const game_drawstate *ds, const grid *g,
2943 int grid_x, int grid_y, int *x, int *y)
2945 *x = grid_x - g->lowest_x;
2946 *y = grid_y - g->lowest_y;
2947 *x = *x * ds->tilesize / g->tilesize;
2948 *y = *y * ds->tilesize / g->tilesize;
2949 *x += BORDER(ds->tilesize);
2950 *y += BORDER(ds->tilesize);
2953 /* Returns (into x,y) position of centre of face for rendering the text clue.
2955 static void face_text_pos(const game_drawstate *ds, const grid *g,
2956 grid_face *f, int *xret, int *yret)
2958 int faceindex = f - g->faces;
2961 * Return the cached position for this face, if we've already
2964 if (ds->textx[faceindex] >= 0) {
2965 *xret = ds->textx[faceindex];
2966 *yret = ds->texty[faceindex];
2971 * Otherwise, use the incentre computed by grid.c and convert it
2972 * to screen coordinates.
2974 grid_find_incentre(f);
2975 grid_to_screen(ds, g, f->ix, f->iy,
2976 &ds->textx[faceindex], &ds->texty[faceindex]);
2978 *xret = ds->textx[faceindex];
2979 *yret = ds->texty[faceindex];
2982 static void face_text_bbox(game_drawstate *ds, grid *g, grid_face *f,
2983 int *x, int *y, int *w, int *h)
2986 face_text_pos(ds, g, f, &xx, &yy);
2988 /* There seems to be a certain amount of trial-and-error involved
2989 * in working out the correct bounding-box for the text. */
2991 *x = xx - ds->tilesize/4 - 1;
2992 *y = yy - ds->tilesize/4 - 3;
2993 *w = ds->tilesize/2 + 2;
2994 *h = ds->tilesize/2 + 5;
2997 static void game_redraw_clue(drawing *dr, game_drawstate *ds,
2998 const game_state *state, int i)
3000 grid *g = state->game_grid;
3001 grid_face *f = g->faces + i;
3005 sprintf(c, "%d", state->clues[i]);
3007 face_text_pos(ds, g, f, &x, &y);
3009 FONT_VARIABLE, ds->tilesize/2,
3010 ALIGN_VCENTRE | ALIGN_HCENTRE,
3011 ds->clue_error[i] ? COL_MISTAKE :
3012 ds->clue_satisfied[i] ? COL_SATISFIED : COL_FOREGROUND, c);
3015 static void edge_bbox(game_drawstate *ds, grid *g, grid_edge *e,
3016 int *x, int *y, int *w, int *h)
3018 int x1 = e->dot1->x;
3019 int y1 = e->dot1->y;
3020 int x2 = e->dot2->x;
3021 int y2 = e->dot2->y;
3022 int xmin, xmax, ymin, ymax;
3024 grid_to_screen(ds, g, x1, y1, &x1, &y1);
3025 grid_to_screen(ds, g, x2, y2, &x2, &y2);
3026 /* Allow extra margin for dots, and thickness of lines */
3027 xmin = min(x1, x2) - 2;
3028 xmax = max(x1, x2) + 2;
3029 ymin = min(y1, y2) - 2;
3030 ymax = max(y1, y2) + 2;
3034 *w = xmax - xmin + 1;
3035 *h = ymax - ymin + 1;
3038 static void dot_bbox(game_drawstate *ds, grid *g, grid_dot *d,
3039 int *x, int *y, int *w, int *h)
3043 grid_to_screen(ds, g, d->x, d->y, &x1, &y1);
3051 static const int loopy_line_redraw_phases[] = {
3052 COL_FAINT, COL_LINEUNKNOWN, COL_FOREGROUND, COL_HIGHLIGHT, COL_MISTAKE
3054 #define NPHASES lenof(loopy_line_redraw_phases)
3056 static void game_redraw_line(drawing *dr, game_drawstate *ds,
3057 const game_state *state, int i, int phase)
3059 grid *g = state->game_grid;
3060 grid_edge *e = g->edges + i;
3064 if (state->line_errors[i])
3065 line_colour = COL_MISTAKE;
3066 else if (state->lines[i] == LINE_UNKNOWN)
3067 line_colour = COL_LINEUNKNOWN;
3068 else if (state->lines[i] == LINE_NO)
3069 line_colour = COL_FAINT;
3070 else if (ds->flashing)
3071 line_colour = COL_HIGHLIGHT;
3073 line_colour = COL_FOREGROUND;
3074 if (line_colour != loopy_line_redraw_phases[phase])
3077 /* Convert from grid to screen coordinates */
3078 grid_to_screen(ds, g, e->dot1->x, e->dot1->y, &x1, &y1);
3079 grid_to_screen(ds, g, e->dot2->x, e->dot2->y, &x2, &y2);
3081 if (line_colour == COL_FAINT) {
3082 static int draw_faint_lines = -1;
3083 if (draw_faint_lines < 0) {
3084 char *env = getenv("LOOPY_FAINT_LINES");
3085 draw_faint_lines = (!env || (env[0] == 'y' ||
3088 if (draw_faint_lines)
3089 draw_line(dr, x1, y1, x2, y2, line_colour);
3091 draw_thick_line(dr, 3.0,
3098 static void game_redraw_dot(drawing *dr, game_drawstate *ds,
3099 const game_state *state, int i)
3101 grid *g = state->game_grid;
3102 grid_dot *d = g->dots + i;
3105 grid_to_screen(ds, g, d->x, d->y, &x, &y);
3106 draw_circle(dr, x, y, 2, COL_FOREGROUND, COL_FOREGROUND);
3109 static int boxes_intersect(int x0, int y0, int w0, int h0,
3110 int x1, int y1, int w1, int h1)
3113 * Two intervals intersect iff neither is wholly on one side of
3114 * the other. Two boxes intersect iff their horizontal and
3115 * vertical intervals both intersect.
3117 return (x0 < x1+w1 && x1 < x0+w0 && y0 < y1+h1 && y1 < y0+h0);
3120 static void game_redraw_in_rect(drawing *dr, game_drawstate *ds,
3121 const game_state *state,
3122 int x, int y, int w, int h)
3124 grid *g = state->game_grid;
3128 clip(dr, x, y, w, h);
3129 draw_rect(dr, x, y, w, h, COL_BACKGROUND);
3131 for (i = 0; i < g->num_faces; i++) {
3132 if (state->clues[i] >= 0) {
3133 face_text_bbox(ds, g, &g->faces[i], &bx, &by, &bw, &bh);
3134 if (boxes_intersect(x, y, w, h, bx, by, bw, bh))
3135 game_redraw_clue(dr, ds, state, i);
3138 for (phase = 0; phase < NPHASES; phase++) {
3139 for (i = 0; i < g->num_edges; i++) {
3140 edge_bbox(ds, g, &g->edges[i], &bx, &by, &bw, &bh);
3141 if (boxes_intersect(x, y, w, h, bx, by, bw, bh))
3142 game_redraw_line(dr, ds, state, i, phase);
3145 for (i = 0; i < g->num_dots; i++) {
3146 dot_bbox(ds, g, &g->dots[i], &bx, &by, &bw, &bh);
3147 if (boxes_intersect(x, y, w, h, bx, by, bw, bh))
3148 game_redraw_dot(dr, ds, state, i);
3152 draw_update(dr, x, y, w, h);
3155 static void game_redraw(drawing *dr, game_drawstate *ds,
3156 const game_state *oldstate, const game_state *state,
3157 int dir, const game_ui *ui,
3158 float animtime, float flashtime)
3160 #define REDRAW_OBJECTS_LIMIT 16 /* Somewhat arbitrary tradeoff */
3162 grid *g = state->game_grid;
3163 int border = BORDER(ds->tilesize);
3166 int redraw_everything = FALSE;
3168 int edges[REDRAW_OBJECTS_LIMIT], nedges = 0;
3169 int faces[REDRAW_OBJECTS_LIMIT], nfaces = 0;
3171 /* Redrawing is somewhat involved.
3173 * An update can theoretically affect an arbitrary number of edges
3174 * (consider, for example, completing or breaking a cycle which doesn't
3175 * satisfy all the clues -- we'll switch many edges between error and
3176 * normal states). On the other hand, redrawing the whole grid takes a
3177 * while, making the game feel sluggish, and many updates are actually
3178 * quite well localized.
3180 * This redraw algorithm attempts to cope with both situations gracefully
3181 * and correctly. For localized changes, we set a clip rectangle, fill
3182 * it with background, and then redraw (a plausible but conservative
3183 * guess at) the objects which intersect the rectangle; if several
3184 * objects need redrawing, we'll do them individually. However, if lots
3185 * of objects are affected, we'll just redraw everything.
3187 * The reason for all of this is that it's just not safe to do the redraw
3188 * piecemeal. If you try to draw an antialiased diagonal line over
3189 * itself, you get a slightly thicker antialiased diagonal line, which
3190 * looks rather ugly after a while.
3192 * So, we take two passes over the grid. The first attempts to work out
3193 * what needs doing, and the second actually does it.
3197 redraw_everything = TRUE;
3199 * But we must still go through the upcoming loops, so that we
3200 * set up stuff in ds correctly for the initial redraw.
3204 /* First, trundle through the faces. */
3205 for (i = 0; i < g->num_faces; i++) {
3206 grid_face *f = g->faces + i;
3207 int sides = f->order;
3210 int n = state->clues[i];
3214 clue_mistake = (face_order(state, i, LINE_YES) > n ||
3215 face_order(state, i, LINE_NO ) > (sides-n));
3216 clue_satisfied = (face_order(state, i, LINE_YES) == n &&
3217 face_order(state, i, LINE_NO ) == (sides-n));
3219 if (clue_mistake != ds->clue_error[i] ||
3220 clue_satisfied != ds->clue_satisfied[i]) {
3221 ds->clue_error[i] = clue_mistake;
3222 ds->clue_satisfied[i] = clue_satisfied;
3223 if (nfaces == REDRAW_OBJECTS_LIMIT)
3224 redraw_everything = TRUE;
3226 faces[nfaces++] = i;
3230 /* Work out what the flash state needs to be. */
3231 if (flashtime > 0 &&
3232 (flashtime <= FLASH_TIME/3 ||
3233 flashtime >= FLASH_TIME*2/3)) {
3234 flash_changed = !ds->flashing;
3235 ds->flashing = TRUE;
3237 flash_changed = ds->flashing;
3238 ds->flashing = FALSE;
3241 /* Now, trundle through the edges. */
3242 for (i = 0; i < g->num_edges; i++) {
3244 state->line_errors[i] ? DS_LINE_ERROR : state->lines[i];
3245 if (new_ds != ds->lines[i] ||
3246 (flash_changed && state->lines[i] == LINE_YES)) {
3247 ds->lines[i] = new_ds;
3248 if (nedges == REDRAW_OBJECTS_LIMIT)
3249 redraw_everything = TRUE;
3251 edges[nedges++] = i;
3255 /* Pass one is now done. Now we do the actual drawing. */
3256 if (redraw_everything) {
3257 int grid_width = g->highest_x - g->lowest_x;
3258 int grid_height = g->highest_y - g->lowest_y;
3259 int w = grid_width * ds->tilesize / g->tilesize;
3260 int h = grid_height * ds->tilesize / g->tilesize;
3262 game_redraw_in_rect(dr, ds, state,
3263 0, 0, w + 2*border + 1, h + 2*border + 1);
3266 /* Right. Now we roll up our sleeves. */
3268 for (i = 0; i < nfaces; i++) {
3269 grid_face *f = g->faces + faces[i];
3272 face_text_bbox(ds, g, f, &x, &y, &w, &h);
3273 game_redraw_in_rect(dr, ds, state, x, y, w, h);
3276 for (i = 0; i < nedges; i++) {
3277 grid_edge *e = g->edges + edges[i];
3280 edge_bbox(ds, g, e, &x, &y, &w, &h);
3281 game_redraw_in_rect(dr, ds, state, x, y, w, h);
3288 static float game_flash_length(const game_state *oldstate,
3289 const game_state *newstate, int dir, game_ui *ui)
3291 if (!oldstate->solved && newstate->solved &&
3292 !oldstate->cheated && !newstate->cheated) {
3299 static int game_status(const game_state *state)
3301 return state->solved ? +1 : 0;
3304 static void game_print_size(const game_params *params, float *x, float *y)
3309 * I'll use 7mm "squares" by default.
3311 game_compute_size(params, 700, &pw, &ph);
3316 static void game_print(drawing *dr, const game_state *state, int tilesize)
3318 int ink = print_mono_colour(dr, 0);
3320 game_drawstate ads, *ds = &ads;
3321 grid *g = state->game_grid;
3323 ds->tilesize = tilesize;
3324 ds->textx = snewn(g->num_faces, int);
3325 ds->texty = snewn(g->num_faces, int);
3326 for (i = 0; i < g->num_faces; i++)
3327 ds->textx[i] = ds->texty[i] = -1;
3329 for (i = 0; i < g->num_dots; i++) {
3331 grid_to_screen(ds, g, g->dots[i].x, g->dots[i].y, &x, &y);
3332 draw_circle(dr, x, y, ds->tilesize / 15, ink, ink);
3338 for (i = 0; i < g->num_faces; i++) {
3339 grid_face *f = g->faces + i;
3340 int clue = state->clues[i];
3344 sprintf(c, "%d", state->clues[i]);
3345 face_text_pos(ds, g, f, &x, &y);
3347 FONT_VARIABLE, ds->tilesize / 2,
3348 ALIGN_VCENTRE | ALIGN_HCENTRE, ink, c);
3355 for (i = 0; i < g->num_edges; i++) {
3356 int thickness = (state->lines[i] == LINE_YES) ? 30 : 150;
3357 grid_edge *e = g->edges + i;
3359 grid_to_screen(ds, g, e->dot1->x, e->dot1->y, &x1, &y1);
3360 grid_to_screen(ds, g, e->dot2->x, e->dot2->y, &x2, &y2);
3361 if (state->lines[i] == LINE_YES)
3363 /* (dx, dy) points from (x1, y1) to (x2, y2).
3364 * The line is then "fattened" in a perpendicular
3365 * direction to create a thin rectangle. */
3366 double d = sqrt(SQ((double)x1 - x2) + SQ((double)y1 - y2));
3367 double dx = (x2 - x1) / d;
3368 double dy = (y2 - y1) / d;
3371 dx = (dx * ds->tilesize) / thickness;
3372 dy = (dy * ds->tilesize) / thickness;
3373 points[0] = x1 + (int)dy;
3374 points[1] = y1 - (int)dx;
3375 points[2] = x1 - (int)dy;
3376 points[3] = y1 + (int)dx;
3377 points[4] = x2 - (int)dy;
3378 points[5] = y2 + (int)dx;
3379 points[6] = x2 + (int)dy;
3380 points[7] = y2 - (int)dx;
3381 draw_polygon(dr, points, 4, ink, ink);
3385 /* Draw a dotted line */
3388 for (j = 1; j < divisions; j++) {
3389 /* Weighted average */
3390 int x = (x1 * (divisions -j) + x2 * j) / divisions;
3391 int y = (y1 * (divisions -j) + y2 * j) / divisions;
3392 draw_circle(dr, x, y, ds->tilesize / thickness, ink, ink);
3402 #define thegame loopy
3405 const struct game thegame = {
3406 "Loopy", "games.loopy", "loopy",
3413 TRUE, game_configure, custom_params,
3421 TRUE, game_can_format_as_text_now, game_text_format,
3429 PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
3432 game_free_drawstate,
3437 TRUE, FALSE, game_print_size, game_print,
3438 FALSE /* wants_statusbar */,
3439 FALSE, game_timing_state,
3440 0, /* mouse_priorities */
3443 #ifdef STANDALONE_SOLVER
3446 * Half-hearted standalone solver. It can't output the solution to
3447 * anything but a square puzzle, and it can't log the deductions
3448 * it makes either. But it can solve square puzzles, and more
3449 * importantly it can use its solver to grade the difficulty of
3450 * any puzzle you give it.
3455 int main(int argc, char **argv)
3459 char *id = NULL, *desc, *err;
3462 #if 0 /* verbose solver not supported here (yet) */
3463 int really_verbose = FALSE;
3466 while (--argc > 0) {
3468 #if 0 /* verbose solver not supported here (yet) */
3469 if (!strcmp(p, "-v")) {
3470 really_verbose = TRUE;
3473 if (!strcmp(p, "-g")) {
3475 } else if (*p == '-') {
3476 fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
3484 fprintf(stderr, "usage: %s [-g | -v] <game_id>\n", argv[0]);
3488 desc = strchr(id, ':');
3490 fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
3495 p = default_params();
3496 decode_params(p, id);
3497 err = validate_desc(p, desc);
3499 fprintf(stderr, "%s: %s\n", argv[0], err);
3502 s = new_game(NULL, p, desc);
3505 * When solving an Easy puzzle, we don't want to bother the
3506 * user with Hard-level deductions. For this reason, we grade
3507 * the puzzle internally before doing anything else.
3509 ret = -1; /* placate optimiser */
3510 for (diff = 0; diff < DIFF_MAX; diff++) {
3511 solver_state *sstate_new;
3512 solver_state *sstate = new_solver_state((game_state *)s, diff);
3514 sstate_new = solve_game_rec(sstate);
3516 if (sstate_new->solver_status == SOLVER_MISTAKE)
3518 else if (sstate_new->solver_status == SOLVER_SOLVED)
3523 free_solver_state(sstate_new);
3524 free_solver_state(sstate);
3530 if (diff == DIFF_MAX) {
3532 printf("Difficulty rating: harder than Hard, or ambiguous\n");
3534 printf("Unable to find a unique solution\n");
3538 printf("Difficulty rating: impossible (no solution exists)\n");
3540 printf("Difficulty rating: %s\n", diffnames[diff]);
3542 solver_state *sstate_new;
3543 solver_state *sstate = new_solver_state((game_state *)s, diff);
3545 /* If we supported a verbose solver, we'd set verbosity here */
3547 sstate_new = solve_game_rec(sstate);
3549 if (sstate_new->solver_status == SOLVER_MISTAKE)
3550 printf("Puzzle is inconsistent\n");
3552 assert(sstate_new->solver_status == SOLVER_SOLVED);
3553 if (s->grid_type == 0) {
3554 fputs(game_text_format(sstate_new->state), stdout);
3556 printf("Unable to output non-square grids\n");
3560 free_solver_state(sstate_new);
3561 free_solver_state(sstate);
3570 /* vim: set shiftwidth=4 tabstop=8: */