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.
86 /* Debugging options */
94 /* ----------------------------------------------------------------------
95 * Struct, enum and function declarations
112 /* Put -1 in a face that doesn't get a clue */
115 /* Array of line states, to store whether each line is
116 * YES, NO or UNKNOWN */
119 unsigned char *line_errors
;
124 /* Used in game_text_format(), so that it knows what type of
125 * grid it's trying to render as ASCII text. */
130 SOLVER_SOLVED
, /* This is the only solution the solver could find */
131 SOLVER_MISTAKE
, /* This is definitely not a solution */
132 SOLVER_AMBIGUOUS
, /* This _might_ be an ambiguous solution */
133 SOLVER_INCOMPLETE
/* This may be a partial solution */
136 /* ------ Solver state ------ */
137 typedef struct solver_state
{
139 enum solver_status solver_status
;
140 /* NB looplen is the number of dots that are joined together at a point, ie a
141 * looplen of 1 means there are no lines to a particular dot */
144 /* Difficulty level of solver. Used by solver functions that want to
145 * vary their behaviour depending on the requested difficulty level. */
151 char *face_yes_count
;
153 char *dot_solved
, *face_solved
;
156 /* Information for Normal level deductions:
157 * For each dline, store a bitmask for whether we know:
158 * (bit 0) at least one is YES
159 * (bit 1) at most one is YES */
162 /* Hard level information */
167 * Difficulty levels. I do some macro ickery here to ensure that my
168 * enum and the various forms of my name list always match up.
171 #define DIFFLIST(A) \
176 #define ENUM(upper,title,lower) DIFF_ ## upper,
177 #define TITLE(upper,title,lower) #title,
178 #define ENCODE(upper,title,lower) #lower
179 #define CONFIG(upper,title,lower) ":" #title
180 enum { DIFFLIST(ENUM
) DIFF_MAX
};
181 static char const *const diffnames
[] = { DIFFLIST(TITLE
) };
182 static char const diffchars
[] = DIFFLIST(ENCODE
);
183 #define DIFFCONFIG DIFFLIST(CONFIG)
186 * Solver routines, sorted roughly in order of computational cost.
187 * The solver will run the faster deductions first, and slower deductions are
188 * only invoked when the faster deductions are unable to make progress.
189 * Each function is associated with a difficulty level, so that the generated
190 * puzzles are solvable by applying only the functions with the chosen
191 * difficulty level or lower.
193 #define SOLVERLIST(A) \
194 A(trivial_deductions, DIFF_EASY) \
195 A(dline_deductions, DIFF_NORMAL) \
196 A(linedsf_deductions, DIFF_HARD) \
197 A(loop_deductions, DIFF_EASY)
198 #define SOLVER_FN_DECL(fn,diff) static int fn(solver_state *);
199 #define SOLVER_FN(fn,diff) &fn,
200 #define SOLVER_DIFF(fn,diff) diff,
201 SOLVERLIST(SOLVER_FN_DECL
)
202 static int (*(solver_fns
[]))(solver_state
*) = { SOLVERLIST(SOLVER_FN
) };
203 static int const solver_diffs
[] = { SOLVERLIST(SOLVER_DIFF
) };
204 const int NUM_SOLVERS
= sizeof(solver_diffs
)/sizeof(*solver_diffs
);
211 /* Grid generation is expensive, so keep a (ref-counted) reference to the
212 * grid for these parameters, and only generate when required. */
216 /* line_drawstate is the same as line_state, but with the extra ERROR
217 * possibility. The drawing code copies line_state to line_drawstate,
218 * except in the case that the line is an error. */
219 enum line_state
{ LINE_YES
, LINE_UNKNOWN
, LINE_NO
};
220 enum line_drawstate
{ DS_LINE_YES
, DS_LINE_UNKNOWN
,
221 DS_LINE_NO
, DS_LINE_ERROR
};
223 #define OPP(line_state) \
227 struct game_drawstate
{
233 char *clue_satisfied
;
236 static char *validate_desc(game_params
*params
, char *desc
);
237 static int dot_order(const game_state
* state
, int i
, char line_type
);
238 static int face_order(const game_state
* state
, int i
, char line_type
);
239 static solver_state
*solve_game_rec(const solver_state
*sstate
);
242 static void check_caches(const solver_state
* sstate
);
244 #define check_caches(s)
247 /* ------- List of grid generators ------- */
248 #define GRIDLIST(A) \
249 A(Squares,grid_new_square,3,3) \
250 A(Triangular,grid_new_triangular,3,3) \
251 A(Honeycomb,grid_new_honeycomb,3,3) \
252 A(Snub-Square,grid_new_snubsquare,3,3) \
253 A(Cairo,grid_new_cairo,3,4) \
254 A(Great-Hexagonal,grid_new_greathexagonal,3,3) \
255 A(Octagonal,grid_new_octagonal,3,3) \
256 A(Kites,grid_new_kites,3,3)
258 #define GRID_NAME(title,fn,amin,omin) #title,
259 #define GRID_CONFIG(title,fn,amin,omin) ":" #title
260 #define GRID_FN(title,fn,amin,omin) &fn,
261 #define GRID_SIZES(title,fn,amin,omin) \
263 "Width and height for this grid type must both be at least " #amin, \
264 "At least one of width and height for this grid type must be at least " #omin,},
265 static char const *const gridnames
[] = { GRIDLIST(GRID_NAME
) };
266 #define GRID_CONFIGS GRIDLIST(GRID_CONFIG)
267 static grid
* (*(grid_fns
[]))(int w
, int h
) = { GRIDLIST(GRID_FN
) };
268 #define NUM_GRID_TYPES (sizeof(grid_fns) / sizeof(grid_fns[0]))
269 static const struct {
272 } grid_size_limits
[] = { GRIDLIST(GRID_SIZES
) };
274 /* Generates a (dynamically allocated) new grid, according to the
275 * type and size requested in params. Does nothing if the grid is already
276 * generated. The allocated grid is owned by the params object, and will be
277 * freed in free_params(). */
278 static void params_generate_grid(game_params
*params
)
280 if (!params
->game_grid
) {
281 params
->game_grid
= grid_fns
[params
->type
](params
->w
, params
->h
);
285 /* ----------------------------------------------------------------------
289 /* General constants */
290 #define PREFERRED_TILE_SIZE 32
291 #define BORDER(tilesize) ((tilesize) / 2)
292 #define FLASH_TIME 0.5F
294 #define BIT_SET(field, bit) ((field) & (1<<(bit)))
296 #define SET_BIT(field, bit) (BIT_SET(field, bit) ? FALSE : \
297 ((field) |= (1<<(bit)), TRUE))
299 #define CLEAR_BIT(field, bit) (BIT_SET(field, bit) ? \
300 ((field) &= ~(1<<(bit)), TRUE) : FALSE)
302 #define CLUE2CHAR(c) \
303 ((c < 0) ? ' ' : c + '0')
305 /* ----------------------------------------------------------------------
306 * General struct manipulation and other straightforward code
309 static game_state
*dup_game(game_state
*state
)
311 game_state
*ret
= snew(game_state
);
313 ret
->game_grid
= state
->game_grid
;
314 ret
->game_grid
->refcount
++;
316 ret
->solved
= state
->solved
;
317 ret
->cheated
= state
->cheated
;
319 ret
->clues
= snewn(state
->game_grid
->num_faces
, signed char);
320 memcpy(ret
->clues
, state
->clues
, state
->game_grid
->num_faces
);
322 ret
->lines
= snewn(state
->game_grid
->num_edges
, char);
323 memcpy(ret
->lines
, state
->lines
, state
->game_grid
->num_edges
);
325 ret
->line_errors
= snewn(state
->game_grid
->num_edges
, unsigned char);
326 memcpy(ret
->line_errors
, state
->line_errors
, state
->game_grid
->num_edges
);
328 ret
->grid_type
= state
->grid_type
;
332 static void free_game(game_state
*state
)
335 grid_free(state
->game_grid
);
338 sfree(state
->line_errors
);
343 static solver_state
*new_solver_state(game_state
*state
, int diff
) {
345 int num_dots
= state
->game_grid
->num_dots
;
346 int num_faces
= state
->game_grid
->num_faces
;
347 int num_edges
= state
->game_grid
->num_edges
;
348 solver_state
*ret
= snew(solver_state
);
350 ret
->state
= dup_game(state
);
352 ret
->solver_status
= SOLVER_INCOMPLETE
;
355 ret
->dotdsf
= snew_dsf(num_dots
);
356 ret
->looplen
= snewn(num_dots
, int);
358 for (i
= 0; i
< num_dots
; i
++) {
362 ret
->dot_solved
= snewn(num_dots
, char);
363 ret
->face_solved
= snewn(num_faces
, char);
364 memset(ret
->dot_solved
, FALSE
, num_dots
);
365 memset(ret
->face_solved
, FALSE
, num_faces
);
367 ret
->dot_yes_count
= snewn(num_dots
, char);
368 memset(ret
->dot_yes_count
, 0, num_dots
);
369 ret
->dot_no_count
= snewn(num_dots
, char);
370 memset(ret
->dot_no_count
, 0, num_dots
);
371 ret
->face_yes_count
= snewn(num_faces
, char);
372 memset(ret
->face_yes_count
, 0, num_faces
);
373 ret
->face_no_count
= snewn(num_faces
, char);
374 memset(ret
->face_no_count
, 0, num_faces
);
376 if (diff
< DIFF_NORMAL
) {
379 ret
->dlines
= snewn(2*num_edges
, char);
380 memset(ret
->dlines
, 0, 2*num_edges
);
383 if (diff
< DIFF_HARD
) {
386 ret
->linedsf
= snew_dsf(state
->game_grid
->num_edges
);
392 static void free_solver_state(solver_state
*sstate
) {
394 free_game(sstate
->state
);
395 sfree(sstate
->dotdsf
);
396 sfree(sstate
->looplen
);
397 sfree(sstate
->dot_solved
);
398 sfree(sstate
->face_solved
);
399 sfree(sstate
->dot_yes_count
);
400 sfree(sstate
->dot_no_count
);
401 sfree(sstate
->face_yes_count
);
402 sfree(sstate
->face_no_count
);
404 /* OK, because sfree(NULL) is a no-op */
405 sfree(sstate
->dlines
);
406 sfree(sstate
->linedsf
);
412 static solver_state
*dup_solver_state(const solver_state
*sstate
) {
413 game_state
*state
= sstate
->state
;
414 int num_dots
= state
->game_grid
->num_dots
;
415 int num_faces
= state
->game_grid
->num_faces
;
416 int num_edges
= state
->game_grid
->num_edges
;
417 solver_state
*ret
= snew(solver_state
);
419 ret
->state
= state
= dup_game(sstate
->state
);
421 ret
->solver_status
= sstate
->solver_status
;
422 ret
->diff
= sstate
->diff
;
424 ret
->dotdsf
= snewn(num_dots
, int);
425 ret
->looplen
= snewn(num_dots
, int);
426 memcpy(ret
->dotdsf
, sstate
->dotdsf
,
427 num_dots
* sizeof(int));
428 memcpy(ret
->looplen
, sstate
->looplen
,
429 num_dots
* sizeof(int));
431 ret
->dot_solved
= snewn(num_dots
, char);
432 ret
->face_solved
= snewn(num_faces
, char);
433 memcpy(ret
->dot_solved
, sstate
->dot_solved
, num_dots
);
434 memcpy(ret
->face_solved
, sstate
->face_solved
, num_faces
);
436 ret
->dot_yes_count
= snewn(num_dots
, char);
437 memcpy(ret
->dot_yes_count
, sstate
->dot_yes_count
, num_dots
);
438 ret
->dot_no_count
= snewn(num_dots
, char);
439 memcpy(ret
->dot_no_count
, sstate
->dot_no_count
, num_dots
);
441 ret
->face_yes_count
= snewn(num_faces
, char);
442 memcpy(ret
->face_yes_count
, sstate
->face_yes_count
, num_faces
);
443 ret
->face_no_count
= snewn(num_faces
, char);
444 memcpy(ret
->face_no_count
, sstate
->face_no_count
, num_faces
);
446 if (sstate
->dlines
) {
447 ret
->dlines
= snewn(2*num_edges
, char);
448 memcpy(ret
->dlines
, sstate
->dlines
,
454 if (sstate
->linedsf
) {
455 ret
->linedsf
= snewn(num_edges
, int);
456 memcpy(ret
->linedsf
, sstate
->linedsf
,
457 num_edges
* sizeof(int));
465 static game_params
*default_params(void)
467 game_params
*ret
= snew(game_params
);
476 ret
->diff
= DIFF_EASY
;
479 ret
->game_grid
= NULL
;
484 static game_params
*dup_params(game_params
*params
)
486 game_params
*ret
= snew(game_params
);
488 *ret
= *params
; /* structure copy */
489 if (ret
->game_grid
) {
490 ret
->game_grid
->refcount
++;
495 static const game_params presets
[] = {
497 { 7, 7, DIFF_EASY
, 0, NULL
},
498 { 7, 7, DIFF_NORMAL
, 0, NULL
},
499 { 7, 7, DIFF_HARD
, 0, NULL
},
500 { 7, 7, DIFF_HARD
, 1, NULL
},
501 { 7, 7, DIFF_HARD
, 2, NULL
},
502 { 5, 5, DIFF_HARD
, 3, NULL
},
503 { 7, 7, DIFF_HARD
, 4, NULL
},
504 { 5, 4, DIFF_HARD
, 5, NULL
},
505 { 5, 5, DIFF_HARD
, 6, NULL
},
506 { 5, 5, DIFF_HARD
, 7, NULL
},
508 { 7, 7, DIFF_EASY
, 0, NULL
},
509 { 10, 10, DIFF_EASY
, 0, NULL
},
510 { 7, 7, DIFF_NORMAL
, 0, NULL
},
511 { 10, 10, DIFF_NORMAL
, 0, NULL
},
512 { 7, 7, DIFF_HARD
, 0, NULL
},
513 { 10, 10, DIFF_HARD
, 0, NULL
},
514 { 10, 10, DIFF_HARD
, 1, NULL
},
515 { 12, 10, DIFF_HARD
, 2, NULL
},
516 { 7, 7, DIFF_HARD
, 3, NULL
},
517 { 9, 9, DIFF_HARD
, 4, NULL
},
518 { 5, 4, DIFF_HARD
, 5, NULL
},
519 { 7, 7, DIFF_HARD
, 6, NULL
},
520 { 5, 5, DIFF_HARD
, 7, NULL
},
524 static int game_fetch_preset(int i
, char **name
, game_params
**params
)
529 if (i
< 0 || i
>= lenof(presets
))
532 tmppar
= snew(game_params
);
533 *tmppar
= presets
[i
];
535 sprintf(buf
, "%dx%d %s - %s", tmppar
->h
, tmppar
->w
,
536 gridnames
[tmppar
->type
], diffnames
[tmppar
->diff
]);
542 static void free_params(game_params
*params
)
544 if (params
->game_grid
) {
545 grid_free(params
->game_grid
);
550 static void decode_params(game_params
*params
, char const *string
)
552 if (params
->game_grid
) {
553 grid_free(params
->game_grid
);
554 params
->game_grid
= NULL
;
556 params
->h
= params
->w
= atoi(string
);
557 params
->diff
= DIFF_EASY
;
558 while (*string
&& isdigit((unsigned char)*string
)) string
++;
559 if (*string
== 'x') {
561 params
->h
= atoi(string
);
562 while (*string
&& isdigit((unsigned char)*string
)) string
++;
564 if (*string
== 't') {
566 params
->type
= atoi(string
);
567 while (*string
&& isdigit((unsigned char)*string
)) string
++;
569 if (*string
== 'd') {
572 for (i
= 0; i
< DIFF_MAX
; i
++)
573 if (*string
== diffchars
[i
])
575 if (*string
) string
++;
579 static char *encode_params(game_params
*params
, int full
)
582 sprintf(str
, "%dx%dt%d", params
->w
, params
->h
, params
->type
);
584 sprintf(str
+ strlen(str
), "d%c", diffchars
[params
->diff
]);
588 static config_item
*game_configure(game_params
*params
)
593 ret
= snewn(5, config_item
);
595 ret
[0].name
= "Width";
596 ret
[0].type
= C_STRING
;
597 sprintf(buf
, "%d", params
->w
);
598 ret
[0].sval
= dupstr(buf
);
601 ret
[1].name
= "Height";
602 ret
[1].type
= C_STRING
;
603 sprintf(buf
, "%d", params
->h
);
604 ret
[1].sval
= dupstr(buf
);
607 ret
[2].name
= "Grid type";
608 ret
[2].type
= C_CHOICES
;
609 ret
[2].sval
= GRID_CONFIGS
;
610 ret
[2].ival
= params
->type
;
612 ret
[3].name
= "Difficulty";
613 ret
[3].type
= C_CHOICES
;
614 ret
[3].sval
= DIFFCONFIG
;
615 ret
[3].ival
= params
->diff
;
625 static game_params
*custom_params(config_item
*cfg
)
627 game_params
*ret
= snew(game_params
);
629 ret
->w
= atoi(cfg
[0].sval
);
630 ret
->h
= atoi(cfg
[1].sval
);
631 ret
->type
= cfg
[2].ival
;
632 ret
->diff
= cfg
[3].ival
;
634 ret
->game_grid
= NULL
;
638 static char *validate_params(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 /* We require that the params pass the test in validate_params and that the
696 * description fills the entire game area */
697 static char *validate_desc(game_params
*params
, char *desc
)
701 params_generate_grid(params
);
702 g
= params
->game_grid
;
704 for (; *desc
; ++desc
) {
705 if (*desc
>= '0' && *desc
<= '9') {
710 count
+= *desc
- 'a' + 1;
713 return "Unknown character in description";
716 if (count
< g
->num_faces
)
717 return "Description too short for board size";
718 if (count
> g
->num_faces
)
719 return "Description too long for board size";
724 /* Sums the lengths of the numbers in range [0,n) */
725 /* See equivalent function in solo.c for justification of this. */
726 static int len_0_to_n(int n
)
728 int len
= 1; /* Counting 0 as a bit of a special case */
731 for (i
= 1; i
< n
; i
*= 10) {
732 len
+= max(n
- i
, 0);
738 static char *encode_solve_move(const game_state
*state
)
743 int num_edges
= state
->game_grid
->num_edges
;
745 /* This is going to return a string representing the moves needed to set
746 * every line in a grid to be the same as the ones in 'state'. The exact
747 * length of this string is predictable. */
749 len
= 1; /* Count the 'S' prefix */
750 /* Numbers in all lines */
751 len
+= len_0_to_n(num_edges
);
752 /* For each line we also have a letter */
755 ret
= snewn(len
+ 1, char);
758 p
+= sprintf(p
, "S");
760 for (i
= 0; i
< num_edges
; i
++) {
761 switch (state
->lines
[i
]) {
763 p
+= sprintf(p
, "%dy", i
);
766 p
+= sprintf(p
, "%dn", i
);
771 /* No point in doing sums like that if they're going to be wrong */
772 assert(strlen(ret
) <= (size_t)len
);
776 static game_ui
*new_ui(game_state
*state
)
781 static void free_ui(game_ui
*ui
)
785 static char *encode_ui(game_ui
*ui
)
790 static void decode_ui(game_ui
*ui
, char *encoding
)
794 static void game_changed_state(game_ui
*ui
, game_state
*oldstate
,
795 game_state
*newstate
)
799 static void game_compute_size(game_params
*params
, int tilesize
,
803 int grid_width
, grid_height
, rendered_width
, rendered_height
;
805 params_generate_grid(params
);
806 g
= params
->game_grid
;
807 grid_width
= g
->highest_x
- g
->lowest_x
;
808 grid_height
= g
->highest_y
- g
->lowest_y
;
809 /* multiply first to minimise rounding error on integer division */
810 rendered_width
= grid_width
* tilesize
/ g
->tilesize
;
811 rendered_height
= grid_height
* tilesize
/ g
->tilesize
;
812 *x
= rendered_width
+ 2 * BORDER(tilesize
) + 1;
813 *y
= rendered_height
+ 2 * BORDER(tilesize
) + 1;
816 static void game_set_size(drawing
*dr
, game_drawstate
*ds
,
817 game_params
*params
, int tilesize
)
819 ds
->tilesize
= tilesize
;
822 static float *game_colours(frontend
*fe
, int *ncolours
)
824 float *ret
= snewn(4 * NCOLOURS
, float);
826 frontend_default_colour(fe
, &ret
[COL_BACKGROUND
* 3]);
828 ret
[COL_FOREGROUND
* 3 + 0] = 0.0F
;
829 ret
[COL_FOREGROUND
* 3 + 1] = 0.0F
;
830 ret
[COL_FOREGROUND
* 3 + 2] = 0.0F
;
832 ret
[COL_LINEUNKNOWN
* 3 + 0] = 0.8F
;
833 ret
[COL_LINEUNKNOWN
* 3 + 1] = 0.8F
;
834 ret
[COL_LINEUNKNOWN
* 3 + 2] = 0.0F
;
836 ret
[COL_HIGHLIGHT
* 3 + 0] = 1.0F
;
837 ret
[COL_HIGHLIGHT
* 3 + 1] = 1.0F
;
838 ret
[COL_HIGHLIGHT
* 3 + 2] = 1.0F
;
840 ret
[COL_MISTAKE
* 3 + 0] = 1.0F
;
841 ret
[COL_MISTAKE
* 3 + 1] = 0.0F
;
842 ret
[COL_MISTAKE
* 3 + 2] = 0.0F
;
844 ret
[COL_SATISFIED
* 3 + 0] = 0.0F
;
845 ret
[COL_SATISFIED
* 3 + 1] = 0.0F
;
846 ret
[COL_SATISFIED
* 3 + 2] = 0.0F
;
848 /* We want the faint lines to be a bit darker than the background.
849 * Except if the background is pretty dark already; then it ought to be a
850 * bit lighter. Oy vey.
852 ret
[COL_FAINT
* 3 + 0] = ret
[COL_BACKGROUND
* 3 + 0] * 0.9F
;
853 ret
[COL_FAINT
* 3 + 1] = ret
[COL_BACKGROUND
* 3 + 1] * 0.9F
;
854 ret
[COL_FAINT
* 3 + 2] = ret
[COL_BACKGROUND
* 3 + 2] * 0.9F
;
856 *ncolours
= NCOLOURS
;
860 static game_drawstate
*game_new_drawstate(drawing
*dr
, game_state
*state
)
862 struct game_drawstate
*ds
= snew(struct game_drawstate
);
863 int num_faces
= state
->game_grid
->num_faces
;
864 int num_edges
= state
->game_grid
->num_edges
;
868 ds
->lines
= snewn(num_edges
, char);
869 ds
->clue_error
= snewn(num_faces
, char);
870 ds
->clue_satisfied
= snewn(num_faces
, char);
873 memset(ds
->lines
, LINE_UNKNOWN
, num_edges
);
874 memset(ds
->clue_error
, 0, num_faces
);
875 memset(ds
->clue_satisfied
, 0, num_faces
);
880 static void game_free_drawstate(drawing
*dr
, game_drawstate
*ds
)
882 sfree(ds
->clue_error
);
883 sfree(ds
->clue_satisfied
);
888 static int game_timing_state(game_state
*state
, game_ui
*ui
)
893 static float game_anim_length(game_state
*oldstate
, game_state
*newstate
,
894 int dir
, game_ui
*ui
)
899 static int game_can_format_as_text_now(game_params
*params
)
901 if (params
->type
!= 0)
906 static char *game_text_format(game_state
*state
)
912 grid
*g
= state
->game_grid
;
915 assert(state
->grid_type
== 0);
917 /* Work out the basic size unit */
918 f
= g
->faces
; /* first face */
919 assert(f
->order
== 4);
920 /* The dots are ordered clockwise, so the two opposite
921 * corners are guaranteed to span the square */
922 cell_size
= abs(f
->dots
[0]->x
- f
->dots
[2]->x
);
924 w
= (g
->highest_x
- g
->lowest_x
) / cell_size
;
925 h
= (g
->highest_y
- g
->lowest_y
) / cell_size
;
927 /* Create a blank "canvas" to "draw" on */
930 ret
= snewn(W
* H
+ 1, char);
931 for (y
= 0; y
< H
; y
++) {
932 for (x
= 0; x
< W
-1; x
++) {
935 ret
[y
*W
+ W
-1] = '\n';
939 /* Fill in edge info */
940 for (i
= 0; i
< g
->num_edges
; i
++) {
941 grid_edge
*e
= g
->edges
+ i
;
942 /* Cell coordinates, from (0,0) to (w-1,h-1) */
943 int x1
= (e
->dot1
->x
- g
->lowest_x
) / cell_size
;
944 int x2
= (e
->dot2
->x
- g
->lowest_x
) / cell_size
;
945 int y1
= (e
->dot1
->y
- g
->lowest_y
) / cell_size
;
946 int y2
= (e
->dot2
->y
- g
->lowest_y
) / cell_size
;
947 /* Midpoint, in canvas coordinates (canvas coordinates are just twice
948 * cell coordinates) */
951 switch (state
->lines
[i
]) {
953 ret
[y
*W
+ x
] = (y1
== y2
) ?
'-' : '|';
959 break; /* already a space */
961 assert(!"Illegal line state");
966 for (i
= 0; i
< g
->num_faces
; i
++) {
970 assert(f
->order
== 4);
971 /* Cell coordinates, from (0,0) to (w-1,h-1) */
972 x1
= (f
->dots
[0]->x
- g
->lowest_x
) / cell_size
;
973 x2
= (f
->dots
[2]->x
- g
->lowest_x
) / cell_size
;
974 y1
= (f
->dots
[0]->y
- g
->lowest_y
) / cell_size
;
975 y2
= (f
->dots
[2]->y
- g
->lowest_y
) / cell_size
;
976 /* Midpoint, in canvas coordinates */
979 ret
[y
*W
+ x
] = CLUE2CHAR(state
->clues
[i
]);
984 /* ----------------------------------------------------------------------
989 static void check_caches(const solver_state
* sstate
)
992 const game_state
*state
= sstate
->state
;
993 const grid
*g
= state
->game_grid
;
995 for (i
= 0; i
< g
->num_dots
; i
++) {
996 assert(dot_order(state
, i
, LINE_YES
) == sstate
->dot_yes_count
[i
]);
997 assert(dot_order(state
, i
, LINE_NO
) == sstate
->dot_no_count
[i
]);
1000 for (i
= 0; i
< g
->num_faces
; i
++) {
1001 assert(face_order(state
, i
, LINE_YES
) == sstate
->face_yes_count
[i
]);
1002 assert(face_order(state
, i
, LINE_NO
) == sstate
->face_no_count
[i
]);
1007 #define check_caches(s) \
1009 fprintf(stderr, "check_caches at line %d\n", __LINE__); \
1013 #endif /* DEBUG_CACHES */
1015 /* ----------------------------------------------------------------------
1016 * Solver utility functions
1019 /* Sets the line (with index i) to the new state 'line_new', and updates
1020 * the cached counts of any affected faces and dots.
1021 * Returns TRUE if this actually changed the line's state. */
1022 static int solver_set_line(solver_state
*sstate
, int i
,
1023 enum line_state line_new
1025 , const char *reason
1029 game_state
*state
= sstate
->state
;
1033 assert(line_new
!= LINE_UNKNOWN
);
1035 check_caches(sstate
);
1037 if (state
->lines
[i
] == line_new
) {
1038 return FALSE
; /* nothing changed */
1040 state
->lines
[i
] = line_new
;
1043 fprintf(stderr
, "solver: set line [%d] to %s (%s)\n",
1044 i
, line_new
== LINE_YES ?
"YES" : "NO",
1048 g
= state
->game_grid
;
1051 /* Update the cache for both dots and both faces affected by this. */
1052 if (line_new
== LINE_YES
) {
1053 sstate
->dot_yes_count
[e
->dot1
- g
->dots
]++;
1054 sstate
->dot_yes_count
[e
->dot2
- g
->dots
]++;
1056 sstate
->face_yes_count
[e
->face1
- g
->faces
]++;
1059 sstate
->face_yes_count
[e
->face2
- g
->faces
]++;
1062 sstate
->dot_no_count
[e
->dot1
- g
->dots
]++;
1063 sstate
->dot_no_count
[e
->dot2
- g
->dots
]++;
1065 sstate
->face_no_count
[e
->face1
- g
->faces
]++;
1068 sstate
->face_no_count
[e
->face2
- g
->faces
]++;
1072 check_caches(sstate
);
1077 #define solver_set_line(a, b, c) \
1078 solver_set_line(a, b, c, __FUNCTION__)
1082 * Merge two dots due to the existence of an edge between them.
1083 * Updates the dsf tracking equivalence classes, and keeps track of
1084 * the length of path each dot is currently a part of.
1085 * Returns TRUE if the dots were already linked, ie if they are part of a
1086 * closed loop, and false otherwise.
1088 static int merge_dots(solver_state
*sstate
, int edge_index
)
1091 grid
*g
= sstate
->state
->game_grid
;
1092 grid_edge
*e
= g
->edges
+ edge_index
;
1094 i
= e
->dot1
- g
->dots
;
1095 j
= e
->dot2
- g
->dots
;
1097 i
= dsf_canonify(sstate
->dotdsf
, i
);
1098 j
= dsf_canonify(sstate
->dotdsf
, j
);
1103 len
= sstate
->looplen
[i
] + sstate
->looplen
[j
];
1104 dsf_merge(sstate
->dotdsf
, i
, j
);
1105 i
= dsf_canonify(sstate
->dotdsf
, i
);
1106 sstate
->looplen
[i
] = len
;
1111 /* Merge two lines because the solver has deduced that they must be either
1112 * identical or opposite. Returns TRUE if this is new information, otherwise
1114 static int merge_lines(solver_state
*sstate
, int i
, int j
, int inverse
1116 , const char *reason
1122 assert(i
< sstate
->state
->game_grid
->num_edges
);
1123 assert(j
< sstate
->state
->game_grid
->num_edges
);
1125 i
= edsf_canonify(sstate
->linedsf
, i
, &inv_tmp
);
1127 j
= edsf_canonify(sstate
->linedsf
, j
, &inv_tmp
);
1130 edsf_merge(sstate
->linedsf
, i
, j
, inverse
);
1134 fprintf(stderr
, "%s [%d] [%d] %s(%s)\n",
1136 inverse ?
"inverse " : "", reason
);
1143 #define merge_lines(a, b, c, d) \
1144 merge_lines(a, b, c, d, __FUNCTION__)
1147 /* Count the number of lines of a particular type currently going into the
1149 static int dot_order(const game_state
* state
, int dot
, char line_type
)
1152 grid
*g
= state
->game_grid
;
1153 grid_dot
*d
= g
->dots
+ dot
;
1156 for (i
= 0; i
< d
->order
; i
++) {
1157 grid_edge
*e
= d
->edges
[i
];
1158 if (state
->lines
[e
- g
->edges
] == line_type
)
1164 /* Count the number of lines of a particular type currently surrounding the
1166 static int face_order(const game_state
* state
, int face
, char line_type
)
1169 grid
*g
= state
->game_grid
;
1170 grid_face
*f
= g
->faces
+ face
;
1173 for (i
= 0; i
< f
->order
; i
++) {
1174 grid_edge
*e
= f
->edges
[i
];
1175 if (state
->lines
[e
- g
->edges
] == line_type
)
1181 /* Set all lines bordering a dot of type old_type to type new_type
1182 * Return value tells caller whether this function actually did anything */
1183 static int dot_setall(solver_state
*sstate
, int dot
,
1184 char old_type
, char new_type
)
1186 int retval
= FALSE
, r
;
1187 game_state
*state
= sstate
->state
;
1192 if (old_type
== new_type
)
1195 g
= state
->game_grid
;
1198 for (i
= 0; i
< d
->order
; i
++) {
1199 int line_index
= d
->edges
[i
] - g
->edges
;
1200 if (state
->lines
[line_index
] == old_type
) {
1201 r
= solver_set_line(sstate
, line_index
, new_type
);
1209 /* Set all lines bordering a face of type old_type to type new_type */
1210 static int face_setall(solver_state
*sstate
, int face
,
1211 char old_type
, char new_type
)
1213 int retval
= FALSE
, r
;
1214 game_state
*state
= sstate
->state
;
1219 if (old_type
== new_type
)
1222 g
= state
->game_grid
;
1223 f
= g
->faces
+ face
;
1225 for (i
= 0; i
< f
->order
; i
++) {
1226 int line_index
= f
->edges
[i
] - g
->edges
;
1227 if (state
->lines
[line_index
] == old_type
) {
1228 r
= solver_set_line(sstate
, line_index
, new_type
);
1236 /* ----------------------------------------------------------------------
1237 * Loop generation and clue removal
1240 /* We're going to store lists of current candidate faces for colouring black
1242 * Each face gets a 'score', which tells us how adding that face right
1243 * now would affect the curliness of the solution loop. We're trying to
1244 * maximise that quantity so will bias our random selection of faces to
1245 * colour those with high scores */
1249 unsigned long random
;
1250 /* No need to store a grid_face* here. The 'face_scores' array will
1251 * be a list of 'face_score' objects, one for each face of the grid, so
1252 * the position (index) within the 'face_scores' array will determine
1253 * which face corresponds to a particular face_score.
1254 * Having a single 'face_scores' array for all faces simplifies memory
1255 * management, and probably improves performance, because we don't have to
1256 * malloc/free each individual face_score, and we don't have to maintain
1257 * a mapping from grid_face* pointers to face_score* pointers.
1261 static int generic_sort_cmpfn(void *v1
, void *v2
, size_t offset
)
1263 struct face_score
*f1
= v1
;
1264 struct face_score
*f2
= v2
;
1267 r
= *(int *)((char *)f2
+ offset
) - *(int *)((char *)f1
+ offset
);
1272 if (f1
->random
< f2
->random
)
1274 else if (f1
->random
> f2
->random
)
1278 * It's _just_ possible that two faces might have been given
1279 * the same random value. In that situation, fall back to
1280 * comparing based on the positions within the face_scores list.
1281 * This introduces a tiny directional bias, but not a significant one.
1286 static int white_sort_cmpfn(void *v1
, void *v2
)
1288 return generic_sort_cmpfn(v1
, v2
, offsetof(struct face_score
,white_score
));
1291 static int black_sort_cmpfn(void *v1
, void *v2
)
1293 return generic_sort_cmpfn(v1
, v2
, offsetof(struct face_score
,black_score
));
1296 enum face_colour
{ FACE_WHITE
, FACE_GREY
, FACE_BLACK
};
1298 /* face should be of type grid_face* here. */
1299 #define FACE_COLOUR(face) \
1300 ( (face) == NULL ? FACE_BLACK : \
1301 board[(face) - g->faces] )
1303 /* 'board' is an array of these enums, indicating which faces are
1304 * currently black/white/grey. 'colour' is FACE_WHITE or FACE_BLACK.
1305 * Returns whether it's legal to colour the given face with this colour. */
1306 static int can_colour_face(grid
*g
, char* board
, int face_index
,
1307 enum face_colour colour
)
1310 grid_face
*test_face
= g
->faces
+ face_index
;
1311 grid_face
*starting_face
, *current_face
;
1313 int current_state
, s
; /* booleans: equal or not-equal to 'colour' */
1314 int found_same_coloured_neighbour
= FALSE
;
1315 assert(board
[face_index
] != colour
);
1317 /* Can only consider a face for colouring if it's adjacent to a face
1318 * with the same colour. */
1319 for (i
= 0; i
< test_face
->order
; i
++) {
1320 grid_edge
*e
= test_face
->edges
[i
];
1321 grid_face
*f
= (e
->face1
== test_face
) ? e
->face2
: e
->face1
;
1322 if (FACE_COLOUR(f
) == colour
) {
1323 found_same_coloured_neighbour
= TRUE
;
1327 if (!found_same_coloured_neighbour
)
1330 /* Need to avoid creating a loop of faces of this colour around some
1331 * differently-coloured faces.
1332 * Also need to avoid meeting a same-coloured face at a corner, with
1333 * other-coloured faces in between. Here's a simple test that (I believe)
1334 * takes care of both these conditions:
1336 * Take the circular path formed by this face's edges, and inflate it
1337 * slightly outwards. Imagine walking around this path and consider
1338 * the faces that you visit in sequence. This will include all faces
1339 * touching the given face, either along an edge or just at a corner.
1340 * Count the number of 'colour'/not-'colour' transitions you encounter, as
1341 * you walk along the complete loop. This will obviously turn out to be
1343 * If 0, we're either in the middle of an "island" of this colour (should
1344 * be impossible as we're not supposed to create black or white loops),
1345 * or we're about to start a new island - also not allowed.
1346 * If 4 or greater, there are too many separate coloured regions touching
1347 * this face, and colouring it would create a loop or a corner-violation.
1348 * The only allowed case is when the count is exactly 2. */
1350 /* i points to a dot around the test face.
1351 * j points to a face around the i^th dot.
1352 * The current face will always be:
1353 * test_face->dots[i]->faces[j]
1354 * We assume dots go clockwise around the test face,
1355 * and faces go clockwise around dots. */
1357 starting_face
= test_face
->dots
[0]->faces
[0];
1358 if (starting_face
== test_face
) {
1360 starting_face
= test_face
->dots
[0]->faces
[1];
1362 current_face
= starting_face
;
1364 current_state
= (FACE_COLOUR(current_face
) == colour
);
1367 /* Advance to next face.
1368 * Need to loop here because it might take several goes to
1372 if (j
== test_face
->dots
[i
]->order
)
1375 if (test_face
->dots
[i
]->faces
[j
] == test_face
) {
1376 /* Advance to next dot round test_face, then
1377 * find current_face around new dot
1378 * and advance to the next face clockwise */
1380 if (i
== test_face
->order
)
1382 for (j
= 0; j
< test_face
->dots
[i
]->order
; j
++) {
1383 if (test_face
->dots
[i
]->faces
[j
] == current_face
)
1386 /* Must actually find current_face around new dot,
1387 * or else something's wrong with the grid. */
1388 assert(j
!= test_face
->dots
[i
]->order
);
1389 /* Found, so advance to next face and try again */
1394 /* (i,j) are now advanced to next face */
1395 current_face
= test_face
->dots
[i
]->faces
[j
];
1396 s
= (FACE_COLOUR(current_face
) == colour
);
1397 if (s
!= current_state
) {
1400 if (transitions
> 2)
1401 return FALSE
; /* no point in continuing */
1403 } while (current_face
!= starting_face
);
1405 return (transitions
== 2) ? TRUE
: FALSE
;
1408 /* Count the number of neighbours of 'face', having colour 'colour' */
1409 static int face_num_neighbours(grid
*g
, char *board
, grid_face
*face
,
1410 enum face_colour colour
)
1412 int colour_count
= 0;
1416 for (i
= 0; i
< face
->order
; i
++) {
1418 f
= (e
->face1
== face
) ? e
->face2
: e
->face1
;
1419 if (FACE_COLOUR(f
) == colour
)
1422 return colour_count
;
1425 /* The 'score' of a face reflects its current desirability for selection
1426 * as the next face to colour white or black. We want to encourage moving
1427 * into grey areas and increasing loopiness, so we give scores according to
1428 * how many of the face's neighbours are currently coloured the same as the
1429 * proposed colour. */
1430 static int face_score(grid
*g
, char *board
, grid_face
*face
,
1431 enum face_colour colour
)
1433 /* Simple formula: score = 0 - num. same-coloured neighbours,
1434 * so a higher score means fewer same-coloured neighbours. */
1435 return -face_num_neighbours(g
, board
, face
, colour
);
1438 /* Generate a new complete set of clues for the given game_state.
1439 * The method is to generate a WHITE/BLACK colouring of all the faces,
1440 * such that the WHITE faces will define the inside of the path, and the
1441 * BLACK faces define the outside.
1442 * To do this, we initially colour all faces GREY. The infinite space outside
1443 * the grid is coloured BLACK, and we choose a random face to colour WHITE.
1444 * Then we gradually grow the BLACK and the WHITE regions, eliminating GREY
1445 * faces, until the grid is filled with BLACK/WHITE. As we grow the regions,
1446 * we avoid creating loops of a single colour, to preserve the topological
1447 * shape of the WHITE and BLACK regions.
1448 * We also try to make the boundary as loopy and twisty as possible, to avoid
1449 * generating paths that are uninteresting.
1450 * The algorithm works by choosing a BLACK/WHITE colour, then choosing a GREY
1451 * face that can be coloured with that colour (without violating the
1452 * topological shape of that region). It's not obvious, but I think this
1453 * algorithm is guaranteed to terminate without leaving any GREY faces behind.
1454 * Indeed, if there are any GREY faces at all, both the WHITE and BLACK
1455 * regions can be grown.
1456 * This is checked using assert()ions, and I haven't seen any failures yet.
1458 * Hand-wavy proof: imagine what can go wrong...
1460 * Could the white faces get completely cut off by the black faces, and still
1461 * leave some grey faces remaining?
1462 * No, because then the black faces would form a loop around both the white
1463 * faces and the grey faces, which is disallowed because we continually
1464 * maintain the correct topological shape of the black region.
1465 * Similarly, the black faces can never get cut off by the white faces. That
1466 * means both the WHITE and BLACK regions always have some room to grow into
1468 * Could it be that we can't colour some GREY face, because there are too many
1469 * WHITE/BLACK transitions as we walk round the face? (see the
1470 * can_colour_face() function for details)
1471 * No. Imagine otherwise, and we see WHITE/BLACK/WHITE/BLACK as we walk
1472 * around the face. The two WHITE faces would be connected by a WHITE path,
1473 * and the BLACK faces would be connected by a BLACK path. These paths would
1474 * have to cross, which is impossible.
1475 * Another thing that could go wrong: perhaps we can't find any GREY face to
1476 * colour WHITE, because it would create a loop-violation or a corner-violation
1477 * with the other WHITE faces?
1478 * This is a little bit tricky to prove impossible. Imagine you have such a
1479 * GREY face (that is, if you coloured it WHITE, you would create a WHITE loop
1480 * or corner violation).
1481 * That would cut all the non-white area into two blobs. One of those blobs
1482 * must be free of BLACK faces (because the BLACK stuff is a connected blob).
1483 * So we have a connected GREY area, completely surrounded by WHITE
1484 * (including the GREY face we've tentatively coloured WHITE).
1485 * A well-known result in graph theory says that you can always find a GREY
1486 * face whose removal leaves the remaining GREY area connected. And it says
1487 * there are at least two such faces, so we can always choose the one that
1488 * isn't the "tentative" GREY face. Colouring that face WHITE leaves
1489 * everything nice and connected, including that "tentative" GREY face which
1490 * acts as a gateway to the rest of the non-WHITE grid.
1492 static void add_full_clues(game_state
*state
, random_state
*rs
)
1494 signed char *clues
= state
->clues
;
1496 grid
*g
= state
->game_grid
;
1498 int num_faces
= g
->num_faces
;
1499 struct face_score
*face_scores
; /* Array of face_score objects */
1500 struct face_score
*fs
; /* Points somewhere in the above list */
1501 struct grid_face
*cur_face
;
1502 tree234
*lightable_faces_sorted
;
1503 tree234
*darkable_faces_sorted
;
1507 board
= snewn(num_faces
, char);
1510 memset(board
, FACE_GREY
, num_faces
);
1512 /* Create and initialise the list of face_scores */
1513 face_scores
= snewn(num_faces
, struct face_score
);
1514 for (i
= 0; i
< num_faces
; i
++) {
1515 face_scores
[i
].random
= random_bits(rs
, 31);
1516 face_scores
[i
].black_score
= face_scores
[i
].white_score
= 0;
1519 /* Colour a random, finite face white. The infinite face is implicitly
1520 * coloured black. Together, they will seed the random growth process
1521 * for the black and white areas. */
1522 i
= random_upto(rs
, num_faces
);
1523 board
[i
] = FACE_WHITE
;
1525 /* We need a way of favouring faces that will increase our loopiness.
1526 * We do this by maintaining a list of all candidate faces sorted by
1527 * their score and choose randomly from that with appropriate skew.
1528 * In order to avoid consistently biasing towards particular faces, we
1529 * need the sort order _within_ each group of scores to be completely
1530 * random. But it would be abusing the hospitality of the tree234 data
1531 * structure if our comparison function were nondeterministic :-). So with
1532 * each face we associate a random number that does not change during a
1533 * particular run of the generator, and use that as a secondary sort key.
1534 * Yes, this means we will be biased towards particular random faces in
1535 * any one run but that doesn't actually matter. */
1537 lightable_faces_sorted
= newtree234(white_sort_cmpfn
);
1538 darkable_faces_sorted
= newtree234(black_sort_cmpfn
);
1540 /* Initialise the lists of lightable and darkable faces. This is
1541 * slightly different from the code inside the while-loop, because we need
1542 * to check every face of the board (the grid structure does not keep a
1543 * list of the infinite face's neighbours). */
1544 for (i
= 0; i
< num_faces
; i
++) {
1545 grid_face
*f
= g
->faces
+ i
;
1546 struct face_score
*fs
= face_scores
+ i
;
1547 if (board
[i
] != FACE_GREY
) continue;
1548 /* We need the full colourability check here, it's not enough simply
1549 * to check neighbourhood. On some grids, a neighbour of the infinite
1550 * face is not necessarily darkable. */
1551 if (can_colour_face(g
, board
, i
, FACE_BLACK
)) {
1552 fs
->black_score
= face_score(g
, board
, f
, FACE_BLACK
);
1553 add234(darkable_faces_sorted
, fs
);
1555 if (can_colour_face(g
, board
, i
, FACE_WHITE
)) {
1556 fs
->white_score
= face_score(g
, board
, f
, FACE_WHITE
);
1557 add234(lightable_faces_sorted
, fs
);
1561 /* Colour faces one at a time until no more faces are colourable. */
1564 enum face_colour colour
;
1565 struct face_score
*fs_white
, *fs_black
;
1566 int c_lightable
= count234(lightable_faces_sorted
);
1567 int c_darkable
= count234(darkable_faces_sorted
);
1568 if (c_lightable
== 0) {
1569 /* No more lightable faces. Because of how the algorithm
1570 * works, there should be no more darkable faces either. */
1571 assert(c_darkable
== 0);
1575 fs_white
= (struct face_score
*)index234(lightable_faces_sorted
, 0);
1576 fs_black
= (struct face_score
*)index234(darkable_faces_sorted
, 0);
1578 /* Choose a colour, and colour the best available face
1579 * with that colour. */
1580 colour
= random_upto(rs
, 2) ? FACE_WHITE
: FACE_BLACK
;
1582 if (colour
== FACE_WHITE
)
1587 i
= fs
- face_scores
;
1588 assert(board
[i
] == FACE_GREY
);
1591 /* Remove this newly-coloured face from the lists. These lists should
1592 * only contain grey faces. */
1593 del234(lightable_faces_sorted
, fs
);
1594 del234(darkable_faces_sorted
, fs
);
1596 /* Remember which face we've just coloured */
1597 cur_face
= g
->faces
+ i
;
1599 /* The face we've just coloured potentially affects the colourability
1600 * and the scores of any neighbouring faces (touching at a corner or
1601 * edge). So the search needs to be conducted around all faces
1602 * touching the one we've just lit. Iterate over its corners, then
1603 * over each corner's faces. For each such face, we remove it from
1604 * the lists, recalculate any scores, then add it back to the lists
1605 * (depending on whether it is lightable, darkable or both). */
1606 for (i
= 0; i
< cur_face
->order
; i
++) {
1607 grid_dot
*d
= cur_face
->dots
[i
];
1608 for (j
= 0; j
< d
->order
; j
++) {
1609 grid_face
*f
= d
->faces
[j
];
1610 int fi
; /* face index of f */
1617 /* If the face is already coloured, it won't be on our
1618 * lightable/darkable lists anyway, so we can skip it without
1619 * bothering with the removal step. */
1620 if (FACE_COLOUR(f
) != FACE_GREY
) continue;
1622 /* Find the face index and face_score* corresponding to f */
1624 fs
= face_scores
+ fi
;
1626 /* Remove from lightable list if it's in there. We do this,
1627 * even if it is still lightable, because the score might
1628 * be different, and we need to remove-then-add to maintain
1629 * correct sort order. */
1630 del234(lightable_faces_sorted
, fs
);
1631 if (can_colour_face(g
, board
, fi
, FACE_WHITE
)) {
1632 fs
->white_score
= face_score(g
, board
, f
, FACE_WHITE
);
1633 add234(lightable_faces_sorted
, fs
);
1635 /* Do the same for darkable list. */
1636 del234(darkable_faces_sorted
, fs
);
1637 if (can_colour_face(g
, board
, fi
, FACE_BLACK
)) {
1638 fs
->black_score
= face_score(g
, board
, f
, FACE_BLACK
);
1639 add234(darkable_faces_sorted
, fs
);
1646 freetree234(lightable_faces_sorted
);
1647 freetree234(darkable_faces_sorted
);
1650 /* The next step requires a shuffled list of all faces */
1651 face_list
= snewn(num_faces
, int);
1652 for (i
= 0; i
< num_faces
; ++i
) {
1655 shuffle(face_list
, num_faces
, sizeof(int), rs
);
1657 /* The above loop-generation algorithm can often leave large clumps
1658 * of faces of one colour. In extreme cases, the resulting path can be
1659 * degenerate and not very satisfying to solve.
1660 * This next step alleviates this problem:
1661 * Go through the shuffled list, and flip the colour of any face we can
1662 * legally flip, and which is adjacent to only one face of the opposite
1663 * colour - this tends to grow 'tendrils' into any clumps.
1664 * Repeat until we can find no more faces to flip. This will
1665 * eventually terminate, because each flip increases the loop's
1666 * perimeter, which cannot increase for ever.
1667 * The resulting path will have maximal loopiness (in the sense that it
1668 * cannot be improved "locally". Unfortunately, this allows a player to
1669 * make some illicit deductions. To combat this (and make the path more
1670 * interesting), we do one final pass making random flips. */
1672 /* Set to TRUE for final pass */
1673 do_random_pass
= FALSE
;
1676 /* Remember whether a flip occurred during this pass */
1677 int flipped
= FALSE
;
1679 for (i
= 0; i
< num_faces
; ++i
) {
1680 int j
= face_list
[i
];
1681 enum face_colour opp
=
1682 (board
[j
] == FACE_WHITE
) ? FACE_BLACK
: FACE_WHITE
;
1683 if (can_colour_face(g
, board
, j
, opp
)) {
1684 grid_face
*face
= g
->faces
+j
;
1685 if (do_random_pass
) {
1686 /* final random pass */
1687 if (!random_upto(rs
, 10))
1690 /* normal pass - flip when neighbour count is 1 */
1691 if (face_num_neighbours(g
, board
, face
, opp
) == 1) {
1699 if (do_random_pass
) break;
1700 if (!flipped
) do_random_pass
= TRUE
;
1705 /* Fill out all the clues by initialising to 0, then iterating over
1706 * all edges and incrementing each clue as we find edges that border
1707 * between BLACK/WHITE faces. While we're at it, we verify that the
1708 * algorithm does work, and there aren't any GREY faces still there. */
1709 memset(clues
, 0, num_faces
);
1710 for (i
= 0; i
< g
->num_edges
; i
++) {
1711 grid_edge
*e
= g
->edges
+ i
;
1712 grid_face
*f1
= e
->face1
;
1713 grid_face
*f2
= e
->face2
;
1714 enum face_colour c1
= FACE_COLOUR(f1
);
1715 enum face_colour c2
= FACE_COLOUR(f2
);
1716 assert(c1
!= FACE_GREY
);
1717 assert(c2
!= FACE_GREY
);
1719 if (f1
) clues
[f1
- g
->faces
]++;
1720 if (f2
) clues
[f2
- g
->faces
]++;
1728 static int game_has_unique_soln(const game_state
*state
, int diff
)
1731 solver_state
*sstate_new
;
1732 solver_state
*sstate
= new_solver_state((game_state
*)state
, diff
);
1734 sstate_new
= solve_game_rec(sstate
);
1736 assert(sstate_new
->solver_status
!= SOLVER_MISTAKE
);
1737 ret
= (sstate_new
->solver_status
== SOLVER_SOLVED
);
1739 free_solver_state(sstate_new
);
1740 free_solver_state(sstate
);
1746 /* Remove clues one at a time at random. */
1747 static game_state
*remove_clues(game_state
*state
, random_state
*rs
,
1751 int num_faces
= state
->game_grid
->num_faces
;
1752 game_state
*ret
= dup_game(state
), *saved_ret
;
1755 /* We need to remove some clues. We'll do this by forming a list of all
1756 * available clues, shuffling it, then going along one at a
1757 * time clearing each clue in turn for which doing so doesn't render the
1758 * board unsolvable. */
1759 face_list
= snewn(num_faces
, int);
1760 for (n
= 0; n
< num_faces
; ++n
) {
1764 shuffle(face_list
, num_faces
, sizeof(int), rs
);
1766 for (n
= 0; n
< num_faces
; ++n
) {
1767 saved_ret
= dup_game(ret
);
1768 ret
->clues
[face_list
[n
]] = -1;
1770 if (game_has_unique_soln(ret
, diff
)) {
1771 free_game(saved_ret
);
1783 static char *new_game_desc(game_params
*params
, random_state
*rs
,
1784 char **aux
, int interactive
)
1786 /* solution and description both use run-length encoding in obvious ways */
1789 game_state
*state
= snew(game_state
);
1790 game_state
*state_new
;
1791 params_generate_grid(params
);
1792 state
->game_grid
= g
= params
->game_grid
;
1794 state
->clues
= snewn(g
->num_faces
, signed char);
1795 state
->lines
= snewn(g
->num_edges
, char);
1796 state
->line_errors
= snewn(g
->num_edges
, unsigned char);
1798 state
->grid_type
= params
->type
;
1802 memset(state
->lines
, LINE_UNKNOWN
, g
->num_edges
);
1803 memset(state
->line_errors
, 0, g
->num_edges
);
1805 state
->solved
= state
->cheated
= FALSE
;
1807 /* Get a new random solvable board with all its clues filled in. Yes, this
1808 * can loop for ever if the params are suitably unfavourable, but
1809 * preventing games smaller than 4x4 seems to stop this happening */
1811 add_full_clues(state
, rs
);
1812 } while (!game_has_unique_soln(state
, params
->diff
));
1814 state_new
= remove_clues(state
, rs
, params
->diff
);
1819 if (params
->diff
> 0 && game_has_unique_soln(state
, params
->diff
-1)) {
1821 fprintf(stderr
, "Rejecting board, it is too easy\n");
1823 goto newboard_please
;
1826 retval
= state_to_text(state
);
1830 assert(!validate_desc(params
, retval
));
1835 static game_state
*new_game(midend
*me
, game_params
*params
, char *desc
)
1838 game_state
*state
= snew(game_state
);
1839 int empties_to_make
= 0;
1841 const char *dp
= desc
;
1843 int num_faces
, num_edges
;
1845 params_generate_grid(params
);
1846 state
->game_grid
= g
= params
->game_grid
;
1848 num_faces
= g
->num_faces
;
1849 num_edges
= g
->num_edges
;
1851 state
->clues
= snewn(num_faces
, signed char);
1852 state
->lines
= snewn(num_edges
, char);
1853 state
->line_errors
= snewn(num_edges
, unsigned char);
1855 state
->solved
= state
->cheated
= FALSE
;
1857 state
->grid_type
= params
->type
;
1859 for (i
= 0; i
< num_faces
; i
++) {
1860 if (empties_to_make
) {
1862 state
->clues
[i
] = -1;
1868 if (n
>= 0 && n
< 10) {
1869 state
->clues
[i
] = n
;
1873 state
->clues
[i
] = -1;
1874 empties_to_make
= n
- 1;
1879 memset(state
->lines
, LINE_UNKNOWN
, num_edges
);
1880 memset(state
->line_errors
, 0, num_edges
);
1884 /* Calculates the line_errors data, and checks if the current state is a
1886 static int check_completion(game_state
*state
)
1888 grid
*g
= state
->game_grid
;
1890 int num_faces
= g
->num_faces
;
1892 int infinite_area
, finite_area
;
1893 int loops_found
= 0;
1894 int found_edge_not_in_loop
= FALSE
;
1896 memset(state
->line_errors
, 0, g
->num_edges
);
1898 /* LL implementation of SGT's idea:
1899 * A loop will partition the grid into an inside and an outside.
1900 * If there is more than one loop, the grid will be partitioned into
1901 * even more distinct regions. We can therefore track equivalence of
1902 * faces, by saying that two faces are equivalent when there is a non-YES
1903 * edge between them.
1904 * We could keep track of the number of connected components, by counting
1905 * the number of dsf-merges that aren't no-ops.
1906 * But we're only interested in 3 separate cases:
1907 * no loops, one loop, more than one loop.
1909 * No loops: all faces are equivalent to the infinite face.
1910 * One loop: only two equivalence classes - finite and infinite.
1911 * >= 2 loops: there are 2 distinct finite regions.
1913 * So we simply make two passes through all the edges.
1914 * In the first pass, we dsf-merge the two faces bordering each non-YES
1916 * In the second pass, we look for YES-edges bordering:
1917 * a) two non-equivalent faces.
1918 * b) two non-equivalent faces, and one of them is part of a different
1919 * finite area from the first finite area we've seen.
1921 * An occurrence of a) means there is at least one loop.
1922 * An occurrence of b) means there is more than one loop.
1923 * Edges satisfying a) are marked as errors.
1925 * While we're at it, we set a flag if we find a YES edge that is not
1927 * This information will help decide, if there's a single loop, whether it
1928 * is a candidate for being a solution (that is, all YES edges are part of
1931 * If there is a candidate loop, we then go through all clues and check
1932 * they are all satisfied. If so, we have found a solution and we can
1933 * unmark all line_errors.
1936 /* Infinite face is at the end - its index is num_faces.
1937 * This macro is just to make this obvious! */
1938 #define INF_FACE num_faces
1939 dsf
= snewn(num_faces
+ 1, int);
1940 dsf_init(dsf
, num_faces
+ 1);
1943 for (i
= 0; i
< g
->num_edges
; i
++) {
1944 grid_edge
*e
= g
->edges
+ i
;
1945 int f1
= e
->face1 ? e
->face1
- g
->faces
: INF_FACE
;
1946 int f2
= e
->face2 ? e
->face2
- g
->faces
: INF_FACE
;
1947 if (state
->lines
[i
] != LINE_YES
)
1948 dsf_merge(dsf
, f1
, f2
);
1952 infinite_area
= dsf_canonify(dsf
, INF_FACE
);
1954 for (i
= 0; i
< g
->num_edges
; i
++) {
1955 grid_edge
*e
= g
->edges
+ i
;
1956 int f1
= e
->face1 ? e
->face1
- g
->faces
: INF_FACE
;
1957 int can1
= dsf_canonify(dsf
, f1
);
1958 int f2
= e
->face2 ? e
->face2
- g
->faces
: INF_FACE
;
1959 int can2
= dsf_canonify(dsf
, f2
);
1960 if (state
->lines
[i
] != LINE_YES
) continue;
1963 /* Faces are equivalent, so this edge not part of a loop */
1964 found_edge_not_in_loop
= TRUE
;
1967 state
->line_errors
[i
] = TRUE
;
1968 if (loops_found
== 0) loops_found
= 1;
1970 /* Don't bother with further checks if we've already found 2 loops */
1971 if (loops_found
== 2) continue;
1973 if (finite_area
== -1) {
1974 /* Found our first finite area */
1975 if (can1
!= infinite_area
)
1981 /* Have we found a second area? */
1982 if (finite_area
!= -1) {
1983 if (can1
!= infinite_area
&& can1
!= finite_area
) {
1987 if (can2
!= infinite_area
&& can2
!= finite_area
) {
1994 printf("loops_found = %d\n", loops_found);
1995 printf("found_edge_not_in_loop = %s\n",
1996 found_edge_not_in_loop ? "TRUE" : "FALSE");
1999 sfree(dsf
); /* No longer need the dsf */
2001 /* Have we found a candidate loop? */
2002 if (loops_found
== 1 && !found_edge_not_in_loop
) {
2003 /* Yes, so check all clues are satisfied */
2004 int found_clue_violation
= FALSE
;
2005 for (i
= 0; i
< num_faces
; i
++) {
2006 int c
= state
->clues
[i
];
2008 if (face_order(state
, i
, LINE_YES
) != c
) {
2009 found_clue_violation
= TRUE
;
2015 if (!found_clue_violation
) {
2016 /* The loop is good */
2017 memset(state
->line_errors
, 0, g
->num_edges
);
2018 return TRUE
; /* No need to bother checking for dot violations */
2022 /* Check for dot violations */
2023 for (i
= 0; i
< g
->num_dots
; i
++) {
2024 int yes
= dot_order(state
, i
, LINE_YES
);
2025 int unknown
= dot_order(state
, i
, LINE_UNKNOWN
);
2026 if ((yes
== 1 && unknown
== 0) || (yes
>= 3)) {
2027 /* violation, so mark all YES edges as errors */
2028 grid_dot
*d
= g
->dots
+ i
;
2030 for (j
= 0; j
< d
->order
; j
++) {
2031 int e
= d
->edges
[j
] - g
->edges
;
2032 if (state
->lines
[e
] == LINE_YES
)
2033 state
->line_errors
[e
] = TRUE
;
2040 /* ----------------------------------------------------------------------
2043 * Our solver modes operate as follows. Each mode also uses the modes above it.
2046 * Just implement the rules of the game.
2048 * Normal and Tricky Modes
2049 * For each (adjacent) pair of lines through each dot we store a bit for
2050 * whether at least one of them is on and whether at most one is on. (If we
2051 * know both or neither is on that's already stored more directly.)
2054 * Use edsf data structure to make equivalence classes of lines that are
2055 * known identical to or opposite to one another.
2060 * For general grids, we consider "dlines" to be pairs of lines joined
2061 * at a dot. The lines must be adjacent around the dot, so we can think of
2062 * a dline as being a dot+face combination. Or, a dot+edge combination where
2063 * the second edge is taken to be the next clockwise edge from the dot.
2064 * Original loopy code didn't have this extra restriction of the lines being
2065 * adjacent. From my tests with square grids, this extra restriction seems to
2066 * take little, if anything, away from the quality of the puzzles.
2067 * A dline can be uniquely identified by an edge/dot combination, given that
2068 * a dline-pair always goes clockwise around its common dot. The edge/dot
2069 * combination can be represented by an edge/bool combination - if bool is
2070 * TRUE, use edge->dot1 else use edge->dot2. So the total number of dlines is
2071 * exactly twice the number of edges in the grid - although the dlines
2072 * spanning the infinite face are not all that useful to the solver.
2073 * Note that, by convention, a dline goes clockwise around its common dot,
2074 * which means the dline goes anti-clockwise around its common face.
2077 /* Helper functions for obtaining an index into an array of dlines, given
2078 * various information. We assume the grid layout conventions about how
2079 * the various lists are interleaved - see grid_make_consistent() for
2082 /* i points to the first edge of the dline pair, reading clockwise around
2084 static int dline_index_from_dot(grid
*g
, grid_dot
*d
, int i
)
2086 grid_edge
*e
= d
->edges
[i
];
2091 if (i2
== d
->order
) i2
= 0;
2094 ret
= 2 * (e
- g
->edges
) + ((e
->dot1
== d
) ?
1 : 0);
2096 printf("dline_index_from_dot: d=%d,i=%d, edges [%d,%d] - %d\n",
2097 (int)(d
- g
->dots
), i
, (int)(e
- g
->edges
),
2098 (int)(e2
- g
->edges
), ret
);
2102 /* i points to the second edge of the dline pair, reading clockwise around
2103 * the face. That is, the edges of the dline, starting at edge{i}, read
2104 * anti-clockwise around the face. By layout conventions, the common dot
2105 * of the dline will be f->dots[i] */
2106 static int dline_index_from_face(grid
*g
, grid_face
*f
, int i
)
2108 grid_edge
*e
= f
->edges
[i
];
2109 grid_dot
*d
= f
->dots
[i
];
2114 if (i2
< 0) i2
+= f
->order
;
2117 ret
= 2 * (e
- g
->edges
) + ((e
->dot1
== d
) ?
1 : 0);
2119 printf("dline_index_from_face: f=%d,i=%d, edges [%d,%d] - %d\n",
2120 (int)(f
- g
->faces
), i
, (int)(e
- g
->edges
),
2121 (int)(e2
- g
->edges
), ret
);
2125 static int is_atleastone(const char *dline_array
, int index
)
2127 return BIT_SET(dline_array
[index
], 0);
2129 static int set_atleastone(char *dline_array
, int index
)
2131 return SET_BIT(dline_array
[index
], 0);
2133 static int is_atmostone(const char *dline_array
, int index
)
2135 return BIT_SET(dline_array
[index
], 1);
2137 static int set_atmostone(char *dline_array
, int index
)
2139 return SET_BIT(dline_array
[index
], 1);
2142 static void array_setall(char *array
, char from
, char to
, int len
)
2144 char *p
= array
, *p_old
= p
;
2145 int len_remaining
= len
;
2147 while ((p
= memchr(p
, from
, len_remaining
))) {
2149 len_remaining
-= p
- p_old
;
2154 /* Helper, called when doing dline dot deductions, in the case where we
2155 * have 4 UNKNOWNs, and two of them (adjacent) have *exactly* one YES between
2156 * them (because of dline atmostone/atleastone).
2157 * On entry, edge points to the first of these two UNKNOWNs. This function
2158 * will find the opposite UNKNOWNS (if they are adjacent to one another)
2159 * and set their corresponding dline to atleastone. (Setting atmostone
2160 * already happens in earlier dline deductions) */
2161 static int dline_set_opp_atleastone(solver_state
*sstate
,
2162 grid_dot
*d
, int edge
)
2164 game_state
*state
= sstate
->state
;
2165 grid
*g
= state
->game_grid
;
2168 for (opp
= 0; opp
< N
; opp
++) {
2169 int opp_dline_index
;
2170 if (opp
== edge
|| opp
== edge
+1 || opp
== edge
-1)
2172 if (opp
== 0 && edge
== N
-1)
2174 if (opp
== N
-1 && edge
== 0)
2177 if (opp2
== N
) opp2
= 0;
2178 /* Check if opp, opp2 point to LINE_UNKNOWNs */
2179 if (state
->lines
[d
->edges
[opp
] - g
->edges
] != LINE_UNKNOWN
)
2181 if (state
->lines
[d
->edges
[opp2
] - g
->edges
] != LINE_UNKNOWN
)
2183 /* Found opposite UNKNOWNS and they're next to each other */
2184 opp_dline_index
= dline_index_from_dot(g
, d
, opp
);
2185 return set_atleastone(sstate
->dlines
, opp_dline_index
);
2191 /* Set pairs of lines around this face which are known to be identical, to
2192 * the given line_state */
2193 static int face_setall_identical(solver_state
*sstate
, int face_index
,
2194 enum line_state line_new
)
2196 /* can[dir] contains the canonical line associated with the line in
2197 * direction dir from the square in question. Similarly inv[dir] is
2198 * whether or not the line in question is inverse to its canonical
2201 game_state
*state
= sstate
->state
;
2202 grid
*g
= state
->game_grid
;
2203 grid_face
*f
= g
->faces
+ face_index
;
2206 int can1
, can2
, inv1
, inv2
;
2208 for (i
= 0; i
< N
; i
++) {
2209 int line1_index
= f
->edges
[i
] - g
->edges
;
2210 if (state
->lines
[line1_index
] != LINE_UNKNOWN
)
2212 for (j
= i
+ 1; j
< N
; j
++) {
2213 int line2_index
= f
->edges
[j
] - g
->edges
;
2214 if (state
->lines
[line2_index
] != LINE_UNKNOWN
)
2217 /* Found two UNKNOWNS */
2218 can1
= edsf_canonify(sstate
->linedsf
, line1_index
, &inv1
);
2219 can2
= edsf_canonify(sstate
->linedsf
, line2_index
, &inv2
);
2220 if (can1
== can2
&& inv1
== inv2
) {
2221 solver_set_line(sstate
, line1_index
, line_new
);
2222 solver_set_line(sstate
, line2_index
, line_new
);
2229 /* Given a dot or face, and a count of LINE_UNKNOWNs, find them and
2230 * return the edge indices into e. */
2231 static void find_unknowns(game_state
*state
,
2232 grid_edge
**edge_list
, /* Edge list to search (from a face or a dot) */
2233 int expected_count
, /* Number of UNKNOWNs (comes from solver's cache) */
2234 int *e
/* Returned edge indices */)
2237 grid
*g
= state
->game_grid
;
2238 while (c
< expected_count
) {
2239 int line_index
= *edge_list
- g
->edges
;
2240 if (state
->lines
[line_index
] == LINE_UNKNOWN
) {
2248 /* If we have a list of edges, and we know whether the number of YESs should
2249 * be odd or even, and there are only a few UNKNOWNs, we can do some simple
2250 * linedsf deductions. This can be used for both face and dot deductions.
2251 * Returns the difficulty level of the next solver that should be used,
2252 * or DIFF_MAX if no progress was made. */
2253 static int parity_deductions(solver_state
*sstate
,
2254 grid_edge
**edge_list
, /* Edge list (from a face or a dot) */
2255 int total_parity
, /* Expected number of YESs modulo 2 (either 0 or 1) */
2258 game_state
*state
= sstate
->state
;
2259 int diff
= DIFF_MAX
;
2260 int *linedsf
= sstate
->linedsf
;
2262 if (unknown_count
== 2) {
2263 /* Lines are known alike/opposite, depending on inv. */
2265 find_unknowns(state
, edge_list
, 2, e
);
2266 if (merge_lines(sstate
, e
[0], e
[1], total_parity
))
2267 diff
= min(diff
, DIFF_HARD
);
2268 } else if (unknown_count
== 3) {
2270 int can
[3]; /* canonical edges */
2271 int inv
[3]; /* whether can[x] is inverse to e[x] */
2272 find_unknowns(state
, edge_list
, 3, e
);
2273 can
[0] = edsf_canonify(linedsf
, e
[0], inv
);
2274 can
[1] = edsf_canonify(linedsf
, e
[1], inv
+1);
2275 can
[2] = edsf_canonify(linedsf
, e
[2], inv
+2);
2276 if (can
[0] == can
[1]) {
2277 if (solver_set_line(sstate
, e
[2], (total_parity
^inv
[0]^inv
[1]) ?
2278 LINE_YES
: LINE_NO
))
2279 diff
= min(diff
, DIFF_EASY
);
2281 if (can
[0] == can
[2]) {
2282 if (solver_set_line(sstate
, e
[1], (total_parity
^inv
[0]^inv
[2]) ?
2283 LINE_YES
: LINE_NO
))
2284 diff
= min(diff
, DIFF_EASY
);
2286 if (can
[1] == can
[2]) {
2287 if (solver_set_line(sstate
, e
[0], (total_parity
^inv
[1]^inv
[2]) ?
2288 LINE_YES
: LINE_NO
))
2289 diff
= min(diff
, DIFF_EASY
);
2291 } else if (unknown_count
== 4) {
2293 int can
[4]; /* canonical edges */
2294 int inv
[4]; /* whether can[x] is inverse to e[x] */
2295 find_unknowns(state
, edge_list
, 4, e
);
2296 can
[0] = edsf_canonify(linedsf
, e
[0], inv
);
2297 can
[1] = edsf_canonify(linedsf
, e
[1], inv
+1);
2298 can
[2] = edsf_canonify(linedsf
, e
[2], inv
+2);
2299 can
[3] = edsf_canonify(linedsf
, e
[3], inv
+3);
2300 if (can
[0] == can
[1]) {
2301 if (merge_lines(sstate
, e
[2], e
[3], total_parity
^inv
[0]^inv
[1]))
2302 diff
= min(diff
, DIFF_HARD
);
2303 } else if (can
[0] == can
[2]) {
2304 if (merge_lines(sstate
, e
[1], e
[3], total_parity
^inv
[0]^inv
[2]))
2305 diff
= min(diff
, DIFF_HARD
);
2306 } else if (can
[0] == can
[3]) {
2307 if (merge_lines(sstate
, e
[1], e
[2], total_parity
^inv
[0]^inv
[3]))
2308 diff
= min(diff
, DIFF_HARD
);
2309 } else if (can
[1] == can
[2]) {
2310 if (merge_lines(sstate
, e
[0], e
[3], total_parity
^inv
[1]^inv
[2]))
2311 diff
= min(diff
, DIFF_HARD
);
2312 } else if (can
[1] == can
[3]) {
2313 if (merge_lines(sstate
, e
[0], e
[2], total_parity
^inv
[1]^inv
[3]))
2314 diff
= min(diff
, DIFF_HARD
);
2315 } else if (can
[2] == can
[3]) {
2316 if (merge_lines(sstate
, e
[0], e
[1], total_parity
^inv
[2]^inv
[3]))
2317 diff
= min(diff
, DIFF_HARD
);
2325 * These are the main solver functions.
2327 * Their return values are diff values corresponding to the lowest mode solver
2328 * that would notice the work that they have done. For example if the normal
2329 * mode solver adds actual lines or crosses, it will return DIFF_EASY as the
2330 * easy mode solver might be able to make progress using that. It doesn't make
2331 * sense for one of them to return a diff value higher than that of the
2334 * Each function returns the lowest value it can, as early as possible, in
2335 * order to try and pass as much work as possible back to the lower level
2336 * solvers which progress more quickly.
2339 /* PROPOSED NEW DESIGN:
2340 * We have a work queue consisting of 'events' notifying us that something has
2341 * happened that a particular solver mode might be interested in. For example
2342 * the hard mode solver might do something that helps the normal mode solver at
2343 * dot [x,y] in which case it will enqueue an event recording this fact. Then
2344 * we pull events off the work queue, and hand each in turn to the solver that
2345 * is interested in them. If a solver reports that it failed we pass the same
2346 * event on to progressively more advanced solvers and the loop detector. Once
2347 * we've exhausted an event, or it has helped us progress, we drop it and
2348 * continue to the next one. The events are sorted first in order of solver
2349 * complexity (easy first) then order of insertion (oldest first).
2350 * Once we run out of events we loop over each permitted solver in turn
2351 * (easiest first) until either a deduction is made (and an event therefore
2352 * emerges) or no further deductions can be made (in which case we've failed).
2355 * * How do we 'loop over' a solver when both dots and squares are concerned.
2356 * Answer: first all squares then all dots.
2359 static int trivial_deductions(solver_state
*sstate
)
2361 int i
, current_yes
, current_no
;
2362 game_state
*state
= sstate
->state
;
2363 grid
*g
= state
->game_grid
;
2364 int diff
= DIFF_MAX
;
2366 /* Per-face deductions */
2367 for (i
= 0; i
< g
->num_faces
; i
++) {
2368 grid_face
*f
= g
->faces
+ i
;
2370 if (sstate
->face_solved
[i
])
2373 current_yes
= sstate
->face_yes_count
[i
];
2374 current_no
= sstate
->face_no_count
[i
];
2376 if (current_yes
+ current_no
== f
->order
) {
2377 sstate
->face_solved
[i
] = TRUE
;
2381 if (state
->clues
[i
] < 0)
2384 if (state
->clues
[i
] < current_yes
) {
2385 sstate
->solver_status
= SOLVER_MISTAKE
;
2388 if (state
->clues
[i
] == current_yes
) {
2389 if (face_setall(sstate
, i
, LINE_UNKNOWN
, LINE_NO
))
2390 diff
= min(diff
, DIFF_EASY
);
2391 sstate
->face_solved
[i
] = TRUE
;
2395 if (f
->order
- state
->clues
[i
] < current_no
) {
2396 sstate
->solver_status
= SOLVER_MISTAKE
;
2399 if (f
->order
- state
->clues
[i
] == current_no
) {
2400 if (face_setall(sstate
, i
, LINE_UNKNOWN
, LINE_YES
))
2401 diff
= min(diff
, DIFF_EASY
);
2402 sstate
->face_solved
[i
] = TRUE
;
2407 check_caches(sstate
);
2409 /* Per-dot deductions */
2410 for (i
= 0; i
< g
->num_dots
; i
++) {
2411 grid_dot
*d
= g
->dots
+ i
;
2412 int yes
, no
, unknown
;
2414 if (sstate
->dot_solved
[i
])
2417 yes
= sstate
->dot_yes_count
[i
];
2418 no
= sstate
->dot_no_count
[i
];
2419 unknown
= d
->order
- yes
- no
;
2423 sstate
->dot_solved
[i
] = TRUE
;
2424 } else if (unknown
== 1) {
2425 dot_setall(sstate
, i
, LINE_UNKNOWN
, LINE_NO
);
2426 diff
= min(diff
, DIFF_EASY
);
2427 sstate
->dot_solved
[i
] = TRUE
;
2429 } else if (yes
== 1) {
2431 sstate
->solver_status
= SOLVER_MISTAKE
;
2433 } else if (unknown
== 1) {
2434 dot_setall(sstate
, i
, LINE_UNKNOWN
, LINE_YES
);
2435 diff
= min(diff
, DIFF_EASY
);
2437 } else if (yes
== 2) {
2439 dot_setall(sstate
, i
, LINE_UNKNOWN
, LINE_NO
);
2440 diff
= min(diff
, DIFF_EASY
);
2442 sstate
->dot_solved
[i
] = TRUE
;
2444 sstate
->solver_status
= SOLVER_MISTAKE
;
2449 check_caches(sstate
);
2454 static int dline_deductions(solver_state
*sstate
)
2456 game_state
*state
= sstate
->state
;
2457 grid
*g
= state
->game_grid
;
2458 char *dlines
= sstate
->dlines
;
2460 int diff
= DIFF_MAX
;
2462 /* ------ Face deductions ------ */
2464 /* Given a set of dline atmostone/atleastone constraints, need to figure
2465 * out if we can deduce any further info. For more general faces than
2466 * squares, this turns out to be a tricky problem.
2467 * The approach taken here is to define (per face) NxN matrices:
2468 * "maxs" and "mins".
2469 * The entries maxs(j,k) and mins(j,k) define the upper and lower limits
2470 * for the possible number of edges that are YES between positions j and k
2471 * going clockwise around the face. Can think of j and k as marking dots
2472 * around the face (recall the labelling scheme: edge0 joins dot0 to dot1,
2473 * edge1 joins dot1 to dot2 etc).
2474 * Trivially, mins(j,j) = maxs(j,j) = 0, and we don't even bother storing
2475 * these. mins(j,j+1) and maxs(j,j+1) are determined by whether edge{j}
2476 * is YES, NO or UNKNOWN. mins(j,j+2) and maxs(j,j+2) are related to
2477 * the dline atmostone/atleastone status for edges j and j+1.
2479 * Then we calculate the remaining entries recursively. We definitely
2481 * mins(j,k) >= { mins(j,u) + mins(u,k) } for any u between j and k.
2482 * This is because any valid placement of YESs between j and k must give
2483 * a valid placement between j and u, and also between u and k.
2484 * I believe it's sufficient to use just the two values of u:
2485 * j+1 and j+2. Seems to work well in practice - the bounds we compute
2486 * are rigorous, even if they might not be best-possible.
2488 * Once we have maxs and mins calculated, we can make inferences about
2489 * each dline{j,j+1} by looking at the possible complementary edge-counts
2490 * mins(j+2,j) and maxs(j+2,j) and comparing these with the face clue.
2491 * As well as dlines, we can make similar inferences about single edges.
2492 * For example, consider a pentagon with clue 3, and we know at most one
2493 * of (edge0, edge1) is YES, and at most one of (edge2, edge3) is YES.
2494 * We could then deduce edge4 is YES, because maxs(0,4) would be 2, so
2495 * that final edge would have to be YES to make the count up to 3.
2498 /* Much quicker to allocate arrays on the stack than the heap, so
2499 * define the largest possible face size, and base our array allocations
2500 * on that. We check this with an assertion, in case someone decides to
2501 * make a grid which has larger faces than this. Note, this algorithm
2502 * could get quite expensive if there are many large faces. */
2503 #define MAX_FACE_SIZE 8
2505 for (i
= 0; i
< g
->num_faces
; i
++) {
2506 int maxs
[MAX_FACE_SIZE
][MAX_FACE_SIZE
];
2507 int mins
[MAX_FACE_SIZE
][MAX_FACE_SIZE
];
2508 grid_face
*f
= g
->faces
+ i
;
2511 int clue
= state
->clues
[i
];
2512 assert(N
<= MAX_FACE_SIZE
);
2513 if (sstate
->face_solved
[i
])
2515 if (clue
< 0) continue;
2517 /* Calculate the (j,j+1) entries */
2518 for (j
= 0; j
< N
; j
++) {
2519 int edge_index
= f
->edges
[j
] - g
->edges
;
2521 enum line_state line1
= state
->lines
[edge_index
];
2522 enum line_state line2
;
2526 maxs
[j
][k
] = (line1
== LINE_NO
) ?
0 : 1;
2527 mins
[j
][k
] = (line1
== LINE_YES
) ?
1 : 0;
2528 /* Calculate the (j,j+2) entries */
2529 dline_index
= dline_index_from_face(g
, f
, k
);
2530 edge_index
= f
->edges
[k
] - g
->edges
;
2531 line2
= state
->lines
[edge_index
];
2537 if (line1
== LINE_NO
) tmp
--;
2538 if (line2
== LINE_NO
) tmp
--;
2539 if (tmp
== 2 && is_atmostone(dlines
, dline_index
))
2545 if (line1
== LINE_YES
) tmp
++;
2546 if (line2
== LINE_YES
) tmp
++;
2547 if (tmp
== 0 && is_atleastone(dlines
, dline_index
))
2552 /* Calculate the (j,j+m) entries for m between 3 and N-1 */
2553 for (m
= 3; m
< N
; m
++) {
2554 for (j
= 0; j
< N
; j
++) {
2562 maxs
[j
][k
] = maxs
[j
][u
] + maxs
[u
][k
];
2563 mins
[j
][k
] = mins
[j
][u
] + mins
[u
][k
];
2564 tmp
= maxs
[j
][v
] + maxs
[v
][k
];
2565 maxs
[j
][k
] = min(maxs
[j
][k
], tmp
);
2566 tmp
= mins
[j
][v
] + mins
[v
][k
];
2567 mins
[j
][k
] = max(mins
[j
][k
], tmp
);
2571 /* See if we can make any deductions */
2572 for (j
= 0; j
< N
; j
++) {
2574 grid_edge
*e
= f
->edges
[j
];
2575 int line_index
= e
- g
->edges
;
2578 if (state
->lines
[line_index
] != LINE_UNKNOWN
)
2583 /* minimum YESs in the complement of this edge */
2584 if (mins
[k
][j
] > clue
) {
2585 sstate
->solver_status
= SOLVER_MISTAKE
;
2588 if (mins
[k
][j
] == clue
) {
2589 /* setting this edge to YES would make at least
2590 * (clue+1) edges - contradiction */
2591 solver_set_line(sstate
, line_index
, LINE_NO
);
2592 diff
= min(diff
, DIFF_EASY
);
2594 if (maxs
[k
][j
] < clue
- 1) {
2595 sstate
->solver_status
= SOLVER_MISTAKE
;
2598 if (maxs
[k
][j
] == clue
- 1) {
2599 /* Only way to satisfy the clue is to set edge{j} as YES */
2600 solver_set_line(sstate
, line_index
, LINE_YES
);
2601 diff
= min(diff
, DIFF_EASY
);
2604 /* More advanced deduction that allows propagation along diagonal
2605 * chains of faces connected by dots, for example, 3-2-...-2-3
2606 * in square grids. */
2607 if (sstate
->diff
>= DIFF_TRICKY
) {
2608 /* Now see if we can make dline deduction for edges{j,j+1} */
2610 if (state
->lines
[e
- g
->edges
] != LINE_UNKNOWN
)
2611 /* Only worth doing this for an UNKNOWN,UNKNOWN pair.
2612 * Dlines where one of the edges is known, are handled in the
2616 dline_index
= dline_index_from_face(g
, f
, k
);
2620 /* minimum YESs in the complement of this dline */
2621 if (mins
[k
][j
] > clue
- 2) {
2622 /* Adding 2 YESs would break the clue */
2623 if (set_atmostone(dlines
, dline_index
))
2624 diff
= min(diff
, DIFF_NORMAL
);
2626 /* maximum YESs in the complement of this dline */
2627 if (maxs
[k
][j
] < clue
) {
2628 /* Adding 2 NOs would mean not enough YESs */
2629 if (set_atleastone(dlines
, dline_index
))
2630 diff
= min(diff
, DIFF_NORMAL
);
2636 if (diff
< DIFF_NORMAL
)
2639 /* ------ Dot deductions ------ */
2641 for (i
= 0; i
< g
->num_dots
; i
++) {
2642 grid_dot
*d
= g
->dots
+ i
;
2644 int yes
, no
, unknown
;
2646 if (sstate
->dot_solved
[i
])
2648 yes
= sstate
->dot_yes_count
[i
];
2649 no
= sstate
->dot_no_count
[i
];
2650 unknown
= N
- yes
- no
;
2652 for (j
= 0; j
< N
; j
++) {
2655 int line1_index
, line2_index
;
2656 enum line_state line1
, line2
;
2659 dline_index
= dline_index_from_dot(g
, d
, j
);
2660 line1_index
= d
->edges
[j
] - g
->edges
;
2661 line2_index
= d
->edges
[k
] - g
->edges
;
2662 line1
= state
->lines
[line1_index
];
2663 line2
= state
->lines
[line2_index
];
2665 /* Infer dline state from line state */
2666 if (line1
== LINE_NO
|| line2
== LINE_NO
) {
2667 if (set_atmostone(dlines
, dline_index
))
2668 diff
= min(diff
, DIFF_NORMAL
);
2670 if (line1
== LINE_YES
|| line2
== LINE_YES
) {
2671 if (set_atleastone(dlines
, dline_index
))
2672 diff
= min(diff
, DIFF_NORMAL
);
2674 /* Infer line state from dline state */
2675 if (is_atmostone(dlines
, dline_index
)) {
2676 if (line1
== LINE_YES
&& line2
== LINE_UNKNOWN
) {
2677 solver_set_line(sstate
, line2_index
, LINE_NO
);
2678 diff
= min(diff
, DIFF_EASY
);
2680 if (line2
== LINE_YES
&& line1
== LINE_UNKNOWN
) {
2681 solver_set_line(sstate
, line1_index
, LINE_NO
);
2682 diff
= min(diff
, DIFF_EASY
);
2685 if (is_atleastone(dlines
, dline_index
)) {
2686 if (line1
== LINE_NO
&& line2
== LINE_UNKNOWN
) {
2687 solver_set_line(sstate
, line2_index
, LINE_YES
);
2688 diff
= min(diff
, DIFF_EASY
);
2690 if (line2
== LINE_NO
&& line1
== LINE_UNKNOWN
) {
2691 solver_set_line(sstate
, line1_index
, LINE_YES
);
2692 diff
= min(diff
, DIFF_EASY
);
2695 /* Deductions that depend on the numbers of lines.
2696 * Only bother if both lines are UNKNOWN, otherwise the
2697 * easy-mode solver (or deductions above) would have taken
2699 if (line1
!= LINE_UNKNOWN
|| line2
!= LINE_UNKNOWN
)
2702 if (yes
== 0 && unknown
== 2) {
2703 /* Both these unknowns must be identical. If we know
2704 * atmostone or atleastone, we can make progress. */
2705 if (is_atmostone(dlines
, dline_index
)) {
2706 solver_set_line(sstate
, line1_index
, LINE_NO
);
2707 solver_set_line(sstate
, line2_index
, LINE_NO
);
2708 diff
= min(diff
, DIFF_EASY
);
2710 if (is_atleastone(dlines
, dline_index
)) {
2711 solver_set_line(sstate
, line1_index
, LINE_YES
);
2712 solver_set_line(sstate
, line2_index
, LINE_YES
);
2713 diff
= min(diff
, DIFF_EASY
);
2717 if (set_atmostone(dlines
, dline_index
))
2718 diff
= min(diff
, DIFF_NORMAL
);
2720 if (set_atleastone(dlines
, dline_index
))
2721 diff
= min(diff
, DIFF_NORMAL
);
2725 /* More advanced deduction that allows propagation along diagonal
2726 * chains of faces connected by dots, for example: 3-2-...-2-3
2727 * in square grids. */
2728 if (sstate
->diff
>= DIFF_TRICKY
) {
2729 /* If we have atleastone set for this dline, infer
2730 * atmostone for each "opposite" dline (that is, each
2731 * dline without edges in common with this one).
2732 * Again, this test is only worth doing if both these
2733 * lines are UNKNOWN. For if one of these lines were YES,
2734 * the (yes == 1) test above would kick in instead. */
2735 if (is_atleastone(dlines
, dline_index
)) {
2737 for (opp
= 0; opp
< N
; opp
++) {
2738 int opp_dline_index
;
2739 if (opp
== j
|| opp
== j
+1 || opp
== j
-1)
2741 if (j
== 0 && opp
== N
-1)
2743 if (j
== N
-1 && opp
== 0)
2745 opp_dline_index
= dline_index_from_dot(g
, d
, opp
);
2746 if (set_atmostone(dlines
, opp_dline_index
))
2747 diff
= min(diff
, DIFF_NORMAL
);
2749 if (yes
== 0 && is_atmostone(dlines
, dline_index
)) {
2750 /* This dline has *exactly* one YES and there are no
2751 * other YESs. This allows more deductions. */
2753 /* Third unknown must be YES */
2754 for (opp
= 0; opp
< N
; opp
++) {
2756 if (opp
== j
|| opp
== k
)
2758 opp_index
= d
->edges
[opp
] - g
->edges
;
2759 if (state
->lines
[opp_index
] == LINE_UNKNOWN
) {
2760 solver_set_line(sstate
, opp_index
,
2762 diff
= min(diff
, DIFF_EASY
);
2765 } else if (unknown
== 4) {
2766 /* Exactly one of opposite UNKNOWNS is YES. We've
2767 * already set atmostone, so set atleastone as
2770 if (dline_set_opp_atleastone(sstate
, d
, j
))
2771 diff
= min(diff
, DIFF_NORMAL
);
2781 static int linedsf_deductions(solver_state
*sstate
)
2783 game_state
*state
= sstate
->state
;
2784 grid
*g
= state
->game_grid
;
2785 char *dlines
= sstate
->dlines
;
2787 int diff
= DIFF_MAX
;
2790 /* ------ Face deductions ------ */
2792 /* A fully-general linedsf deduction seems overly complicated
2793 * (I suspect the problem is NP-complete, though in practice it might just
2794 * be doable because faces are limited in size).
2795 * For simplicity, we only consider *pairs* of LINE_UNKNOWNS that are
2796 * known to be identical. If setting them both to YES (or NO) would break
2797 * the clue, set them to NO (or YES). */
2799 for (i
= 0; i
< g
->num_faces
; i
++) {
2800 int N
, yes
, no
, unknown
;
2803 if (sstate
->face_solved
[i
])
2805 clue
= state
->clues
[i
];
2809 N
= g
->faces
[i
].order
;
2810 yes
= sstate
->face_yes_count
[i
];
2811 if (yes
+ 1 == clue
) {
2812 if (face_setall_identical(sstate
, i
, LINE_NO
))
2813 diff
= min(diff
, DIFF_EASY
);
2815 no
= sstate
->face_no_count
[i
];
2816 if (no
+ 1 == N
- clue
) {
2817 if (face_setall_identical(sstate
, i
, LINE_YES
))
2818 diff
= min(diff
, DIFF_EASY
);
2821 /* Reload YES count, it might have changed */
2822 yes
= sstate
->face_yes_count
[i
];
2823 unknown
= N
- no
- yes
;
2825 /* Deductions with small number of LINE_UNKNOWNs, based on overall
2826 * parity of lines. */
2827 diff_tmp
= parity_deductions(sstate
, g
->faces
[i
].edges
,
2828 (clue
- yes
) % 2, unknown
);
2829 diff
= min(diff
, diff_tmp
);
2832 /* ------ Dot deductions ------ */
2833 for (i
= 0; i
< g
->num_dots
; i
++) {
2834 grid_dot
*d
= g
->dots
+ i
;
2837 int yes
, no
, unknown
;
2838 /* Go through dlines, and do any dline<->linedsf deductions wherever
2839 * we find two UNKNOWNS. */
2840 for (j
= 0; j
< N
; j
++) {
2841 int dline_index
= dline_index_from_dot(g
, d
, j
);
2844 int can1
, can2
, inv1
, inv2
;
2846 line1_index
= d
->edges
[j
] - g
->edges
;
2847 if (state
->lines
[line1_index
] != LINE_UNKNOWN
)
2850 if (j2
== N
) j2
= 0;
2851 line2_index
= d
->edges
[j2
] - g
->edges
;
2852 if (state
->lines
[line2_index
] != LINE_UNKNOWN
)
2854 /* Infer dline flags from linedsf */
2855 can1
= edsf_canonify(sstate
->linedsf
, line1_index
, &inv1
);
2856 can2
= edsf_canonify(sstate
->linedsf
, line2_index
, &inv2
);
2857 if (can1
== can2
&& inv1
!= inv2
) {
2858 /* These are opposites, so set dline atmostone/atleastone */
2859 if (set_atmostone(dlines
, dline_index
))
2860 diff
= min(diff
, DIFF_NORMAL
);
2861 if (set_atleastone(dlines
, dline_index
))
2862 diff
= min(diff
, DIFF_NORMAL
);
2865 /* Infer linedsf from dline flags */
2866 if (is_atmostone(dlines
, dline_index
)
2867 && is_atleastone(dlines
, dline_index
)) {
2868 if (merge_lines(sstate
, line1_index
, line2_index
, 1))
2869 diff
= min(diff
, DIFF_HARD
);
2873 /* Deductions with small number of LINE_UNKNOWNs, based on overall
2874 * parity of lines. */
2875 yes
= sstate
->dot_yes_count
[i
];
2876 no
= sstate
->dot_no_count
[i
];
2877 unknown
= N
- yes
- no
;
2878 diff_tmp
= parity_deductions(sstate
, d
->edges
,
2880 diff
= min(diff
, diff_tmp
);
2883 /* ------ Edge dsf deductions ------ */
2885 /* If the state of a line is known, deduce the state of its canonical line
2886 * too, and vice versa. */
2887 for (i
= 0; i
< g
->num_edges
; i
++) {
2890 can
= edsf_canonify(sstate
->linedsf
, i
, &inv
);
2893 s
= sstate
->state
->lines
[can
];
2894 if (s
!= LINE_UNKNOWN
) {
2895 if (solver_set_line(sstate
, i
, inv ?
OPP(s
) : s
))
2896 diff
= min(diff
, DIFF_EASY
);
2898 s
= sstate
->state
->lines
[i
];
2899 if (s
!= LINE_UNKNOWN
) {
2900 if (solver_set_line(sstate
, can
, inv ?
OPP(s
) : s
))
2901 diff
= min(diff
, DIFF_EASY
);
2909 static int loop_deductions(solver_state
*sstate
)
2911 int edgecount
= 0, clues
= 0, satclues
= 0, sm1clues
= 0;
2912 game_state
*state
= sstate
->state
;
2913 grid
*g
= state
->game_grid
;
2914 int shortest_chainlen
= g
->num_dots
;
2915 int loop_found
= FALSE
;
2917 int progress
= FALSE
;
2921 * Go through the grid and update for all the new edges.
2922 * Since merge_dots() is idempotent, the simplest way to
2923 * do this is just to update for _all_ the edges.
2924 * Also, while we're here, we count the edges.
2926 for (i
= 0; i
< g
->num_edges
; i
++) {
2927 if (state
->lines
[i
] == LINE_YES
) {
2928 loop_found
|= merge_dots(sstate
, i
);
2934 * Count the clues, count the satisfied clues, and count the
2935 * satisfied-minus-one clues.
2937 for (i
= 0; i
< g
->num_faces
; i
++) {
2938 int c
= state
->clues
[i
];
2940 int o
= sstate
->face_yes_count
[i
];
2949 for (i
= 0; i
< g
->num_dots
; ++i
) {
2951 sstate
->looplen
[dsf_canonify(sstate
->dotdsf
, i
)];
2952 if (dots_connected
> 1)
2953 shortest_chainlen
= min(shortest_chainlen
, dots_connected
);
2956 assert(sstate
->solver_status
== SOLVER_INCOMPLETE
);
2958 if (satclues
== clues
&& shortest_chainlen
== edgecount
) {
2959 sstate
->solver_status
= SOLVER_SOLVED
;
2960 /* This discovery clearly counts as progress, even if we haven't
2961 * just added any lines or anything */
2963 goto finished_loop_deductionsing
;
2967 * Now go through looking for LINE_UNKNOWN edges which
2968 * connect two dots that are already in the same
2969 * equivalence class. If we find one, test to see if the
2970 * loop it would create is a solution.
2972 for (i
= 0; i
< g
->num_edges
; i
++) {
2973 grid_edge
*e
= g
->edges
+ i
;
2974 int d1
= e
->dot1
- g
->dots
;
2975 int d2
= e
->dot2
- g
->dots
;
2977 if (state
->lines
[i
] != LINE_UNKNOWN
)
2980 eqclass
= dsf_canonify(sstate
->dotdsf
, d1
);
2981 if (eqclass
!= dsf_canonify(sstate
->dotdsf
, d2
))
2984 val
= LINE_NO
; /* loop is bad until proven otherwise */
2987 * This edge would form a loop. Next
2988 * question: how long would the loop be?
2989 * Would it equal the total number of edges
2990 * (plus the one we'd be adding if we added
2993 if (sstate
->looplen
[eqclass
] == edgecount
+ 1) {
2997 * This edge would form a loop which
2998 * took in all the edges in the entire
2999 * grid. So now we need to work out
3000 * whether it would be a valid solution
3001 * to the puzzle, which means we have to
3002 * check if it satisfies all the clues.
3003 * This means that every clue must be
3004 * either satisfied or satisfied-minus-
3005 * 1, and also that the number of
3006 * satisfied-minus-1 clues must be at
3007 * most two and they must lie on either
3008 * side of this edge.
3012 int f
= e
->face1
- g
->faces
;
3013 int c
= state
->clues
[f
];
3014 if (c
>= 0 && sstate
->face_yes_count
[f
] == c
- 1)
3018 int f
= e
->face2
- g
->faces
;
3019 int c
= state
->clues
[f
];
3020 if (c
>= 0 && sstate
->face_yes_count
[f
] == c
- 1)
3023 if (sm1clues
== sm1_nearby
&&
3024 sm1clues
+ satclues
== clues
) {
3025 val
= LINE_YES
; /* loop is good! */
3030 * Right. Now we know that adding this edge
3031 * would form a loop, and we know whether
3032 * that loop would be a viable solution or
3035 * If adding this edge produces a solution,
3036 * then we know we've found _a_ solution but
3037 * we don't know that it's _the_ solution -
3038 * if it were provably the solution then
3039 * we'd have deduced this edge some time ago
3040 * without the need to do loop detection. So
3041 * in this state we return SOLVER_AMBIGUOUS,
3042 * which has the effect that hitting Solve
3043 * on a user-provided puzzle will fill in a
3044 * solution but using the solver to
3045 * construct new puzzles won't consider this
3046 * a reasonable deduction for the user to
3049 progress
= solver_set_line(sstate
, i
, val
);
3050 assert(progress
== TRUE
);
3051 if (val
== LINE_YES
) {
3052 sstate
->solver_status
= SOLVER_AMBIGUOUS
;
3053 goto finished_loop_deductionsing
;
3057 finished_loop_deductionsing
:
3058 return progress ? DIFF_EASY
: DIFF_MAX
;
3061 /* This will return a dynamically allocated solver_state containing the (more)
3063 static solver_state
*solve_game_rec(const solver_state
*sstate_start
)
3065 solver_state
*sstate
;
3067 /* Index of the solver we should call next. */
3070 /* As a speed-optimisation, we avoid re-running solvers that we know
3071 * won't make any progress. This happens when a high-difficulty
3072 * solver makes a deduction that can only help other high-difficulty
3074 * For example: if a new 'dline' flag is set by dline_deductions, the
3075 * trivial_deductions solver cannot do anything with this information.
3076 * If we've already run the trivial_deductions solver (because it's
3077 * earlier in the list), there's no point running it again.
3079 * Therefore: if a solver is earlier in the list than "threshold_index",
3080 * we don't bother running it if it's difficulty level is less than
3083 int threshold_diff
= 0;
3084 int threshold_index
= 0;
3086 sstate
= dup_solver_state(sstate_start
);
3088 check_caches(sstate
);
3090 while (i
< NUM_SOLVERS
) {
3091 if (sstate
->solver_status
== SOLVER_MISTAKE
)
3093 if (sstate
->solver_status
== SOLVER_SOLVED
||
3094 sstate
->solver_status
== SOLVER_AMBIGUOUS
) {
3095 /* solver finished */
3099 if ((solver_diffs
[i
] >= threshold_diff
|| i
>= threshold_index
)
3100 && solver_diffs
[i
] <= sstate
->diff
) {
3101 /* current_solver is eligible, so use it */
3102 int next_diff
= solver_fns
[i
](sstate
);
3103 if (next_diff
!= DIFF_MAX
) {
3104 /* solver made progress, so use new thresholds and
3105 * start again at top of list. */
3106 threshold_diff
= next_diff
;
3107 threshold_index
= i
;
3112 /* current_solver is ineligible, or failed to make progress, so
3113 * go to the next solver in the list */
3117 if (sstate
->solver_status
== SOLVER_SOLVED
||
3118 sstate
->solver_status
== SOLVER_AMBIGUOUS
) {
3119 /* s/LINE_UNKNOWN/LINE_NO/g */
3120 array_setall(sstate
->state
->lines
, LINE_UNKNOWN
, LINE_NO
,
3121 sstate
->state
->game_grid
->num_edges
);
3128 static char *solve_game(game_state
*state
, game_state
*currstate
,
3129 char *aux
, char **error
)
3132 solver_state
*sstate
, *new_sstate
;
3134 sstate
= new_solver_state(state
, DIFF_MAX
);
3135 new_sstate
= solve_game_rec(sstate
);
3137 if (new_sstate
->solver_status
== SOLVER_SOLVED
) {
3138 soln
= encode_solve_move(new_sstate
->state
);
3139 } else if (new_sstate
->solver_status
== SOLVER_AMBIGUOUS
) {
3140 soln
= encode_solve_move(new_sstate
->state
);
3141 /**error = "Solver found ambiguous solutions"; */
3143 soln
= encode_solve_move(new_sstate
->state
);
3144 /**error = "Solver failed"; */
3147 free_solver_state(new_sstate
);
3148 free_solver_state(sstate
);
3153 /* ----------------------------------------------------------------------
3154 * Drawing and mouse-handling
3157 static char *interpret_move(game_state
*state
, game_ui
*ui
, game_drawstate
*ds
,
3158 int x
, int y
, int button
)
3160 grid
*g
= state
->game_grid
;
3164 char button_char
= ' ';
3165 enum line_state old_state
;
3167 button
&= ~MOD_MASK
;
3169 /* Convert mouse-click (x,y) to grid coordinates */
3170 x
-= BORDER(ds
->tilesize
);
3171 y
-= BORDER(ds
->tilesize
);
3172 x
= x
* g
->tilesize
/ ds
->tilesize
;
3173 y
= y
* g
->tilesize
/ ds
->tilesize
;
3177 e
= grid_nearest_edge(g
, x
, y
);
3183 /* I think it's only possible to play this game with mouse clicks, sorry */
3184 /* Maybe will add mouse drag support some time */
3185 old_state
= state
->lines
[i
];
3189 switch (old_state
) {
3203 switch (old_state
) {
3218 sprintf(buf
, "%d%c", i
, (int)button_char
);
3224 static game_state
*execute_move(game_state
*state
, char *move
)
3227 game_state
*newstate
= dup_game(state
);
3229 if (move
[0] == 'S') {
3231 newstate
->cheated
= TRUE
;
3236 if (i
< 0 || i
>= newstate
->game_grid
->num_edges
)
3238 move
+= strspn(move
, "1234567890");
3239 switch (*(move
++)) {
3241 newstate
->lines
[i
] = LINE_YES
;
3244 newstate
->lines
[i
] = LINE_NO
;
3247 newstate
->lines
[i
] = LINE_UNKNOWN
;
3255 * Check for completion.
3257 if (check_completion(newstate
))
3258 newstate
->solved
= TRUE
;
3263 free_game(newstate
);
3267 /* ----------------------------------------------------------------------
3271 /* Convert from grid coordinates to screen coordinates */
3272 static void grid_to_screen(const game_drawstate
*ds
, const grid
*g
,
3273 int grid_x
, int grid_y
, int *x
, int *y
)
3275 *x
= grid_x
- g
->lowest_x
;
3276 *y
= grid_y
- g
->lowest_y
;
3277 *x
= *x
* ds
->tilesize
/ g
->tilesize
;
3278 *y
= *y
* ds
->tilesize
/ g
->tilesize
;
3279 *x
+= BORDER(ds
->tilesize
);
3280 *y
+= BORDER(ds
->tilesize
);
3283 /* Returns (into x,y) position of centre of face for rendering the text clue.
3285 static void face_text_pos(const game_drawstate
*ds
, const grid
*g
,
3286 const grid_face
*f
, int *x
, int *y
)
3290 /* Simplest solution is the centroid. Might not work in some cases. */
3292 /* Another algorithm to look into:
3293 * Find the midpoints of the sides, find the bounding-box,
3294 * then take the centre of that. */
3296 /* Best solution probably involves incentres (inscribed circles) */
3298 int sx
= 0, sy
= 0; /* sums */
3299 for (i
= 0; i
< f
->order
; i
++) {
3300 grid_dot
*d
= f
->dots
[i
];
3307 /* convert to screen coordinates */
3308 grid_to_screen(ds
, g
, sx
, sy
, x
, y
);
3311 static void game_redraw(drawing
*dr
, game_drawstate
*ds
, game_state
*oldstate
,
3312 game_state
*state
, int dir
, game_ui
*ui
,
3313 float animtime
, float flashtime
)
3315 grid
*g
= state
->game_grid
;
3316 int border
= BORDER(ds
->tilesize
);
3319 int line_colour
, flash_changed
;
3325 * The initial contents of the window are not guaranteed and
3326 * can vary with front ends. To be on the safe side, all games
3327 * should start by drawing a big background-colour rectangle
3328 * covering the whole window.
3330 int grid_width
= g
->highest_x
- g
->lowest_x
;
3331 int grid_height
= g
->highest_y
- g
->lowest_y
;
3332 int w
= grid_width
* ds
->tilesize
/ g
->tilesize
;
3333 int h
= grid_height
* ds
->tilesize
/ g
->tilesize
;
3334 draw_rect(dr
, 0, 0, w
+ 2 * border
+ 1, h
+ 2 * border
+ 1,
3338 for (i
= 0; i
< g
->num_faces
; i
++) {
3342 c
[0] = CLUE2CHAR(state
->clues
[i
]);
3345 face_text_pos(ds
, g
, f
, &x
, &y
);
3346 draw_text(dr
, x
, y
, FONT_VARIABLE
, ds
->tilesize
/2,
3347 ALIGN_VCENTRE
| ALIGN_HCENTRE
, COL_FOREGROUND
, c
);
3349 draw_update(dr
, 0, 0, w
+ 2 * border
, h
+ 2 * border
);
3352 if (flashtime
> 0 &&
3353 (flashtime
<= FLASH_TIME
/3 ||
3354 flashtime
>= FLASH_TIME
*2/3)) {
3355 flash_changed
= !ds
->flashing
;
3356 ds
->flashing
= TRUE
;
3358 flash_changed
= ds
->flashing
;
3359 ds
->flashing
= FALSE
;
3362 /* Some platforms may perform anti-aliasing, which may prevent clean
3363 * repainting of lines when the colour is changed.
3364 * If a line needs to be over-drawn in a different colour, erase a
3365 * bounding-box around the line, then flag all nearby objects for redraw.
3368 const char redraw_flag
= (char)(1<<7);
3369 for (i
= 0; i
< g
->num_edges
; i
++) {
3370 char prev_ds
= (ds
->lines
[i
] & ~redraw_flag
);
3371 char new_ds
= state
->lines
[i
];
3372 if (state
->line_errors
[i
])
3373 new_ds
= DS_LINE_ERROR
;
3375 /* If we're changing state, AND
3376 * the previous state was a coloured line */
3377 if ((prev_ds
!= new_ds
) && (prev_ds
!= LINE_NO
)) {
3378 grid_edge
*e
= g
->edges
+ i
;
3379 int x1
= e
->dot1
->x
;
3380 int y1
= e
->dot1
->y
;
3381 int x2
= e
->dot2
->x
;
3382 int y2
= e
->dot2
->y
;
3383 int xmin
, xmax
, ymin
, ymax
;
3385 grid_to_screen(ds
, g
, x1
, y1
, &x1
, &y1
);
3386 grid_to_screen(ds
, g
, x2
, y2
, &x2
, &y2
);
3387 /* Allow extra margin for dots, and thickness of lines */
3388 xmin
= min(x1
, x2
) - 2;
3389 xmax
= max(x1
, x2
) + 2;
3390 ymin
= min(y1
, y2
) - 2;
3391 ymax
= max(y1
, y2
) + 2;
3392 /* For testing, I find it helpful to change COL_BACKGROUND
3393 * to COL_SATISFIED here. */
3394 draw_rect(dr
, xmin
, ymin
, xmax
- xmin
+ 1, ymax
- ymin
+ 1,
3396 draw_update(dr
, xmin
, ymin
, xmax
- xmin
+ 1, ymax
- ymin
+ 1);
3398 /* Mark nearby lines for redraw */
3399 for (j
= 0; j
< e
->dot1
->order
; j
++)
3400 ds
->lines
[e
->dot1
->edges
[j
] - g
->edges
] |= redraw_flag
;
3401 for (j
= 0; j
< e
->dot2
->order
; j
++)
3402 ds
->lines
[e
->dot2
->edges
[j
] - g
->edges
] |= redraw_flag
;
3403 /* Mark nearby clues for redraw. Use a value that is
3404 * neither TRUE nor FALSE for this. */
3406 ds
->clue_error
[e
->face1
- g
->faces
] = 2;
3408 ds
->clue_error
[e
->face2
- g
->faces
] = 2;
3413 /* Redraw clue colours if necessary */
3414 for (i
= 0; i
< g
->num_faces
; i
++) {
3415 grid_face
*f
= g
->faces
+ i
;
3416 int sides
= f
->order
;
3418 n
= state
->clues
[i
];
3422 c
[0] = CLUE2CHAR(n
);
3425 clue_mistake
= (face_order(state
, i
, LINE_YES
) > n
||
3426 face_order(state
, i
, LINE_NO
) > (sides
-n
));
3428 clue_satisfied
= (face_order(state
, i
, LINE_YES
) == n
&&
3429 face_order(state
, i
, LINE_NO
) == (sides
-n
));
3431 if (clue_mistake
!= ds
->clue_error
[i
]
3432 || clue_satisfied
!= ds
->clue_satisfied
[i
]) {
3434 face_text_pos(ds
, g
, f
, &x
, &y
);
3435 /* There seems to be a certain amount of trial-and-error
3436 * involved in working out the correct bounding-box for
3438 draw_rect(dr
, x
- ds
->tilesize
/4 - 1, y
- ds
->tilesize
/4 - 3,
3439 ds
->tilesize
/2 + 2, ds
->tilesize
/2 + 5,
3442 FONT_VARIABLE
, ds
->tilesize
/2,
3443 ALIGN_VCENTRE
| ALIGN_HCENTRE
,
3444 clue_mistake ? COL_MISTAKE
:
3445 clue_satisfied ? COL_SATISFIED
: COL_FOREGROUND
, c
);
3446 draw_update(dr
, x
- ds
->tilesize
/4 - 1, y
- ds
->tilesize
/4 - 3,
3447 ds
->tilesize
/2 + 2, ds
->tilesize
/2 + 5);
3449 ds
->clue_error
[i
] = clue_mistake
;
3450 ds
->clue_satisfied
[i
] = clue_satisfied
;
3452 /* Sometimes, the bounding-box encroaches into the surrounding
3453 * lines (particularly if the window is resized fairly small).
3454 * So redraw them. */
3455 for (j
= 0; j
< f
->order
; j
++)
3456 ds
->lines
[f
->edges
[j
] - g
->edges
] = -1;
3461 for (i
= 0; i
< g
->num_edges
; i
++) {
3462 grid_edge
*e
= g
->edges
+ i
;
3464 int xmin
, ymin
, xmax
, ymax
;
3465 char new_ds
, need_draw
;
3466 new_ds
= state
->lines
[i
];
3467 if (state
->line_errors
[i
])
3468 new_ds
= DS_LINE_ERROR
;
3469 need_draw
= (new_ds
!= ds
->lines
[i
]) ? TRUE
: FALSE
;
3470 if (flash_changed
&& (state
->lines
[i
] == LINE_YES
))
3473 need_draw
= TRUE
; /* draw everything at the start */
3474 ds
->lines
[i
] = new_ds
;
3477 if (state
->line_errors
[i
])
3478 line_colour
= COL_MISTAKE
;
3479 else if (state
->lines
[i
] == LINE_UNKNOWN
)
3480 line_colour
= COL_LINEUNKNOWN
;
3481 else if (state
->lines
[i
] == LINE_NO
)
3482 line_colour
= COL_FAINT
;
3483 else if (ds
->flashing
)
3484 line_colour
= COL_HIGHLIGHT
;
3486 line_colour
= COL_FOREGROUND
;
3488 /* Convert from grid to screen coordinates */
3489 grid_to_screen(ds
, g
, e
->dot1
->x
, e
->dot1
->y
, &x1
, &y1
);
3490 grid_to_screen(ds
, g
, e
->dot2
->x
, e
->dot2
->y
, &x2
, &y2
);
3497 if (line_colour
== COL_FAINT
) {
3498 static int draw_faint_lines
= -1;
3499 if (draw_faint_lines
< 0) {
3500 char *env
= getenv("LOOPY_FAINT_LINES");
3501 draw_faint_lines
= (!env
|| (env
[0] == 'y' ||
3504 if (draw_faint_lines
)
3505 draw_line(dr
, x1
, y1
, x2
, y2
, line_colour
);
3507 /* (dx, dy) points roughly from (x1, y1) to (x2, y2).
3508 * The line is then "fattened" in a (roughly) perpendicular
3509 * direction to create a thin rectangle. */
3510 int dx
= (x1
> x2
) ?
-1 : ((x1
< x2
) ?
1 : 0);
3511 int dy
= (y1
> y2
) ?
-1 : ((y1
< y2
) ?
1 : 0);
3513 points
[0] = x1
+ dy
;
3514 points
[1] = y1
- dx
;
3515 points
[2] = x1
- dy
;
3516 points
[3] = y1
+ dx
;
3517 points
[4] = x2
- dy
;
3518 points
[5] = y2
+ dx
;
3519 points
[6] = x2
+ dy
;
3520 points
[7] = y2
- dx
;
3521 draw_polygon(dr
, points
, 4, line_colour
, line_colour
);
3524 /* Draw dots at ends of the line */
3525 draw_circle(dr
, x1
, y1
, 2, COL_FOREGROUND
, COL_FOREGROUND
);
3526 draw_circle(dr
, x2
, y2
, 2, COL_FOREGROUND
, COL_FOREGROUND
);
3528 draw_update(dr
, xmin
-2, ymin
-2, xmax
- xmin
+ 4, ymax
- ymin
+ 4);
3533 for (i
= 0; i
< g
->num_dots
; i
++) {
3534 grid_dot
*d
= g
->dots
+ i
;
3536 grid_to_screen(ds
, g
, d
->x
, d
->y
, &x
, &y
);
3537 draw_circle(dr
, x
, y
, 2, COL_FOREGROUND
, COL_FOREGROUND
);
3543 static float game_flash_length(game_state
*oldstate
, game_state
*newstate
,
3544 int dir
, game_ui
*ui
)
3546 if (!oldstate
->solved
&& newstate
->solved
&&
3547 !oldstate
->cheated
&& !newstate
->cheated
) {
3554 static void game_print_size(game_params
*params
, float *x
, float *y
)
3559 * I'll use 7mm "squares" by default.
3561 game_compute_size(params
, 700, &pw
, &ph
);
3566 static void game_print(drawing
*dr
, game_state
*state
, int tilesize
)
3568 int ink
= print_mono_colour(dr
, 0);
3570 game_drawstate ads
, *ds
= &ads
;
3571 grid
*g
= state
->game_grid
;
3573 game_set_size(dr
, ds
, NULL
, tilesize
);
3575 for (i
= 0; i
< g
->num_dots
; i
++) {
3577 grid_to_screen(ds
, g
, g
->dots
[i
].x
, g
->dots
[i
].y
, &x
, &y
);
3578 draw_circle(dr
, x
, y
, ds
->tilesize
/ 15, ink
, ink
);
3584 for (i
= 0; i
< g
->num_faces
; i
++) {
3585 grid_face
*f
= g
->faces
+ i
;
3586 int clue
= state
->clues
[i
];
3590 c
[0] = CLUE2CHAR(clue
);
3592 face_text_pos(ds
, g
, f
, &x
, &y
);
3594 FONT_VARIABLE
, ds
->tilesize
/ 2,
3595 ALIGN_VCENTRE
| ALIGN_HCENTRE
, ink
, c
);
3602 for (i
= 0; i
< g
->num_edges
; i
++) {
3603 int thickness
= (state
->lines
[i
] == LINE_YES
) ?
30 : 150;
3604 grid_edge
*e
= g
->edges
+ i
;
3606 grid_to_screen(ds
, g
, e
->dot1
->x
, e
->dot1
->y
, &x1
, &y1
);
3607 grid_to_screen(ds
, g
, e
->dot2
->x
, e
->dot2
->y
, &x2
, &y2
);
3608 if (state
->lines
[i
] == LINE_YES
)
3610 /* (dx, dy) points from (x1, y1) to (x2, y2).
3611 * The line is then "fattened" in a perpendicular
3612 * direction to create a thin rectangle. */
3613 double d
= sqrt(SQ((double)x1
- x2
) + SQ((double)y1
- y2
));
3614 double dx
= (x2
- x1
) / d
;
3615 double dy
= (y2
- y1
) / d
;
3618 dx
= (dx
* ds
->tilesize
) / thickness
;
3619 dy
= (dy
* ds
->tilesize
) / thickness
;
3620 points
[0] = x1
+ (int)dy
;
3621 points
[1] = y1
- (int)dx
;
3622 points
[2] = x1
- (int)dy
;
3623 points
[3] = y1
+ (int)dx
;
3624 points
[4] = x2
- (int)dy
;
3625 points
[5] = y2
+ (int)dx
;
3626 points
[6] = x2
+ (int)dy
;
3627 points
[7] = y2
- (int)dx
;
3628 draw_polygon(dr
, points
, 4, ink
, ink
);
3632 /* Draw a dotted line */
3635 for (j
= 1; j
< divisions
; j
++) {
3636 /* Weighted average */
3637 int x
= (x1
* (divisions
-j
) + x2
* j
) / divisions
;
3638 int y
= (y1
* (divisions
-j
) + y2
* j
) / divisions
;
3639 draw_circle(dr
, x
, y
, ds
->tilesize
/ thickness
, ink
, ink
);
3646 #define thegame loopy
3649 const struct game thegame
= {
3650 "Loopy", "games.loopy", "loopy",
3657 TRUE
, game_configure
, custom_params
,
3665 TRUE
, game_can_format_as_text_now
, game_text_format
,
3673 PREFERRED_TILE_SIZE
, game_compute_size
, game_set_size
,
3676 game_free_drawstate
,
3680 TRUE
, FALSE
, game_print_size
, game_print
,
3681 FALSE
/* wants_statusbar */,
3682 FALSE
, game_timing_state
,
3683 0, /* mouse_priorities */
3686 #ifdef STANDALONE_SOLVER
3689 * Half-hearted standalone solver. It can't output the solution to
3690 * anything but a square puzzle, and it can't log the deductions
3691 * it makes either. But it can solve square puzzles, and more
3692 * importantly it can use its solver to grade the difficulty of
3693 * any puzzle you give it.
3698 int main(int argc
, char **argv
)
3702 char *id
= NULL
, *desc
, *err
;
3705 #if 0 /* verbose solver not supported here (yet) */
3706 int really_verbose
= FALSE
;
3709 while (--argc
> 0) {
3711 #if 0 /* verbose solver not supported here (yet) */
3712 if (!strcmp(p
, "-v")) {
3713 really_verbose
= TRUE
;
3716 if (!strcmp(p
, "-g")) {
3718 } else if (*p
== '-') {
3719 fprintf(stderr
, "%s: unrecognised option `%s'\n", argv
[0], p
);
3727 fprintf(stderr
, "usage: %s [-g | -v] <game_id>\n", argv
[0]);
3731 desc
= strchr(id
, ':');
3733 fprintf(stderr
, "%s: game id expects a colon in it\n", argv
[0]);
3738 p
= default_params();
3739 decode_params(p
, id
);
3740 err
= validate_desc(p
, desc
);
3742 fprintf(stderr
, "%s: %s\n", argv
[0], err
);
3745 s
= new_game(NULL
, p
, desc
);
3748 * When solving an Easy puzzle, we don't want to bother the
3749 * user with Hard-level deductions. For this reason, we grade
3750 * the puzzle internally before doing anything else.
3752 ret
= -1; /* placate optimiser */
3753 for (diff
= 0; diff
< DIFF_MAX
; diff
++) {
3754 solver_state
*sstate_new
;
3755 solver_state
*sstate
= new_solver_state((game_state
*)s
, diff
);
3757 sstate_new
= solve_game_rec(sstate
);
3759 if (sstate_new
->solver_status
== SOLVER_MISTAKE
)
3761 else if (sstate_new
->solver_status
== SOLVER_SOLVED
)
3766 free_solver_state(sstate_new
);
3767 free_solver_state(sstate
);
3773 if (diff
== DIFF_MAX
) {
3775 printf("Difficulty rating: harder than Hard, or ambiguous\n");
3777 printf("Unable to find a unique solution\n");
3781 printf("Difficulty rating: impossible (no solution exists)\n");
3783 printf("Difficulty rating: %s\n", diffnames
[diff
]);
3785 solver_state
*sstate_new
;
3786 solver_state
*sstate
= new_solver_state((game_state
*)s
, diff
);
3788 /* If we supported a verbose solver, we'd set verbosity here */
3790 sstate_new
= solve_game_rec(sstate
);
3792 if (sstate_new
->solver_status
== SOLVER_MISTAKE
)
3793 printf("Puzzle is inconsistent\n");
3795 assert(sstate_new
->solver_status
== SOLVER_SOLVED
);
3796 if (s
->grid_type
== 0) {
3797 fputs(game_text_format(sstate_new
->state
), stdout
);
3799 printf("Unable to output non-square grids\n");
3803 free_solver_state(sstate_new
);
3804 free_solver_state(sstate
);