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
110 grid
*game_grid
; /* ref-counted (internally) */
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 static const int NUM_SOLVERS
= sizeof(solver_diffs
)/sizeof(*solver_diffs
);
212 /* line_drawstate is the same as line_state, but with the extra ERROR
213 * possibility. The drawing code copies line_state to line_drawstate,
214 * except in the case that the line is an error. */
215 enum line_state
{ LINE_YES
, LINE_UNKNOWN
, LINE_NO
};
216 enum line_drawstate
{ DS_LINE_YES
, DS_LINE_UNKNOWN
,
217 DS_LINE_NO
, DS_LINE_ERROR
};
219 #define OPP(line_state) \
223 struct game_drawstate
{
230 char *clue_satisfied
;
233 static char *validate_desc(game_params
*params
, char *desc
);
234 static int dot_order(const game_state
* state
, int i
, char line_type
);
235 static int face_order(const game_state
* state
, int i
, char line_type
);
236 static solver_state
*solve_game_rec(const solver_state
*sstate
);
239 static void check_caches(const solver_state
* sstate
);
241 #define check_caches(s)
244 /* ------- List of grid generators ------- */
245 #define GRIDLIST(A) \
246 A(Squares,GRID_SQUARE,3,3) \
247 A(Triangular,GRID_TRIANGULAR,3,3) \
248 A(Honeycomb,GRID_HONEYCOMB,3,3) \
249 A(Snub-Square,GRID_SNUBSQUARE,3,3) \
250 A(Cairo,GRID_CAIRO,3,4) \
251 A(Great-Hexagonal,GRID_GREATHEXAGONAL,3,3) \
252 A(Octagonal,GRID_OCTAGONAL,3,3) \
253 A(Kites,GRID_KITE,3,3) \
254 A(Floret,GRID_FLORET,1,2) \
255 A(Dodecagonal,GRID_DODECAGONAL,2,2) \
256 A(Great-Dodecagonal,GRID_GREATDODECAGONAL,2,2) \
257 A(Penrose (kite/dart),GRID_PENROSE_P2,3,3) \
258 A(Penrose (rhombs),GRID_PENROSE_P3,3,3)
260 #define GRID_NAME(title,type,amin,omin) #title,
261 #define GRID_CONFIG(title,type,amin,omin) ":" #title
262 #define GRID_TYPE(title,type,amin,omin) type,
263 #define GRID_SIZES(title,type,amin,omin) \
265 "Width and height for this grid type must both be at least " #amin, \
266 "At least one of width and height for this grid type must be at least " #omin,},
267 static char const *const gridnames
[] = { GRIDLIST(GRID_NAME
) };
268 #define GRID_CONFIGS GRIDLIST(GRID_CONFIG)
269 static grid_type grid_types
[] = { GRIDLIST(GRID_TYPE
) };
270 #define NUM_GRID_TYPES (sizeof(grid_types) / sizeof(grid_types[0]))
271 static const struct {
274 } grid_size_limits
[] = { GRIDLIST(GRID_SIZES
) };
276 /* Generates a (dynamically allocated) new grid, according to the
277 * type and size requested in params. Does nothing if the grid is already
279 static grid
*loopy_generate_grid(game_params
*params
, char *grid_desc
)
281 return grid_new(grid_types
[params
->type
], params
->w
, params
->h
, grid_desc
);
284 /* ----------------------------------------------------------------------
288 /* General constants */
289 #define PREFERRED_TILE_SIZE 32
290 #define BORDER(tilesize) ((tilesize) / 2)
291 #define FLASH_TIME 0.5F
293 #define BIT_SET(field, bit) ((field) & (1<<(bit)))
295 #define SET_BIT(field, bit) (BIT_SET(field, bit) ? FALSE : \
296 ((field) |= (1<<(bit)), TRUE))
298 #define CLEAR_BIT(field, bit) (BIT_SET(field, bit) ? \
299 ((field) &= ~(1<<(bit)), TRUE) : FALSE)
301 #define CLUE2CHAR(c) \
302 ((c < 0) ? ' ' : c < 10 ? c + '0' : c - 10 + 'A')
304 /* ----------------------------------------------------------------------
305 * General struct manipulation and other straightforward code
308 static game_state
*dup_game(game_state
*state
)
310 game_state
*ret
= snew(game_state
);
312 ret
->game_grid
= state
->game_grid
;
313 ret
->game_grid
->refcount
++;
315 ret
->solved
= state
->solved
;
316 ret
->cheated
= state
->cheated
;
318 ret
->clues
= snewn(state
->game_grid
->num_faces
, signed char);
319 memcpy(ret
->clues
, state
->clues
, state
->game_grid
->num_faces
);
321 ret
->lines
= snewn(state
->game_grid
->num_edges
, char);
322 memcpy(ret
->lines
, state
->lines
, state
->game_grid
->num_edges
);
324 ret
->line_errors
= snewn(state
->game_grid
->num_edges
, unsigned char);
325 memcpy(ret
->line_errors
, state
->line_errors
, state
->game_grid
->num_edges
);
327 ret
->grid_type
= state
->grid_type
;
331 static void free_game(game_state
*state
)
334 grid_free(state
->game_grid
);
337 sfree(state
->line_errors
);
342 static solver_state
*new_solver_state(game_state
*state
, int diff
) {
344 int num_dots
= state
->game_grid
->num_dots
;
345 int num_faces
= state
->game_grid
->num_faces
;
346 int num_edges
= state
->game_grid
->num_edges
;
347 solver_state
*ret
= snew(solver_state
);
349 ret
->state
= dup_game(state
);
351 ret
->solver_status
= SOLVER_INCOMPLETE
;
354 ret
->dotdsf
= snew_dsf(num_dots
);
355 ret
->looplen
= snewn(num_dots
, int);
357 for (i
= 0; i
< num_dots
; i
++) {
361 ret
->dot_solved
= snewn(num_dots
, char);
362 ret
->face_solved
= snewn(num_faces
, char);
363 memset(ret
->dot_solved
, FALSE
, num_dots
);
364 memset(ret
->face_solved
, FALSE
, num_faces
);
366 ret
->dot_yes_count
= snewn(num_dots
, char);
367 memset(ret
->dot_yes_count
, 0, num_dots
);
368 ret
->dot_no_count
= snewn(num_dots
, char);
369 memset(ret
->dot_no_count
, 0, num_dots
);
370 ret
->face_yes_count
= snewn(num_faces
, char);
371 memset(ret
->face_yes_count
, 0, num_faces
);
372 ret
->face_no_count
= snewn(num_faces
, char);
373 memset(ret
->face_no_count
, 0, num_faces
);
375 if (diff
< DIFF_NORMAL
) {
378 ret
->dlines
= snewn(2*num_edges
, char);
379 memset(ret
->dlines
, 0, 2*num_edges
);
382 if (diff
< DIFF_HARD
) {
385 ret
->linedsf
= snew_dsf(state
->game_grid
->num_edges
);
391 static void free_solver_state(solver_state
*sstate
) {
393 free_game(sstate
->state
);
394 sfree(sstate
->dotdsf
);
395 sfree(sstate
->looplen
);
396 sfree(sstate
->dot_solved
);
397 sfree(sstate
->face_solved
);
398 sfree(sstate
->dot_yes_count
);
399 sfree(sstate
->dot_no_count
);
400 sfree(sstate
->face_yes_count
);
401 sfree(sstate
->face_no_count
);
403 /* OK, because sfree(NULL) is a no-op */
404 sfree(sstate
->dlines
);
405 sfree(sstate
->linedsf
);
411 static solver_state
*dup_solver_state(const solver_state
*sstate
) {
412 game_state
*state
= sstate
->state
;
413 int num_dots
= state
->game_grid
->num_dots
;
414 int num_faces
= state
->game_grid
->num_faces
;
415 int num_edges
= state
->game_grid
->num_edges
;
416 solver_state
*ret
= snew(solver_state
);
418 ret
->state
= state
= dup_game(sstate
->state
);
420 ret
->solver_status
= sstate
->solver_status
;
421 ret
->diff
= sstate
->diff
;
423 ret
->dotdsf
= snewn(num_dots
, int);
424 ret
->looplen
= snewn(num_dots
, int);
425 memcpy(ret
->dotdsf
, sstate
->dotdsf
,
426 num_dots
* sizeof(int));
427 memcpy(ret
->looplen
, sstate
->looplen
,
428 num_dots
* sizeof(int));
430 ret
->dot_solved
= snewn(num_dots
, char);
431 ret
->face_solved
= snewn(num_faces
, char);
432 memcpy(ret
->dot_solved
, sstate
->dot_solved
, num_dots
);
433 memcpy(ret
->face_solved
, sstate
->face_solved
, num_faces
);
435 ret
->dot_yes_count
= snewn(num_dots
, char);
436 memcpy(ret
->dot_yes_count
, sstate
->dot_yes_count
, num_dots
);
437 ret
->dot_no_count
= snewn(num_dots
, char);
438 memcpy(ret
->dot_no_count
, sstate
->dot_no_count
, num_dots
);
440 ret
->face_yes_count
= snewn(num_faces
, char);
441 memcpy(ret
->face_yes_count
, sstate
->face_yes_count
, num_faces
);
442 ret
->face_no_count
= snewn(num_faces
, char);
443 memcpy(ret
->face_no_count
, sstate
->face_no_count
, num_faces
);
445 if (sstate
->dlines
) {
446 ret
->dlines
= snewn(2*num_edges
, char);
447 memcpy(ret
->dlines
, sstate
->dlines
,
453 if (sstate
->linedsf
) {
454 ret
->linedsf
= snewn(num_edges
, int);
455 memcpy(ret
->linedsf
, sstate
->linedsf
,
456 num_edges
* sizeof(int));
464 static game_params
*default_params(void)
466 game_params
*ret
= snew(game_params
);
475 ret
->diff
= DIFF_EASY
;
481 static game_params
*dup_params(game_params
*params
)
483 game_params
*ret
= snew(game_params
);
485 *ret
= *params
; /* structure copy */
489 static const game_params presets
[] = {
491 { 7, 7, DIFF_EASY
, 0 },
492 { 7, 7, DIFF_NORMAL
, 0 },
493 { 7, 7, DIFF_HARD
, 0 },
494 { 7, 7, DIFF_HARD
, 1 },
495 { 7, 7, DIFF_HARD
, 2 },
496 { 5, 5, DIFF_HARD
, 3 },
497 { 7, 7, DIFF_HARD
, 4 },
498 { 5, 4, DIFF_HARD
, 5 },
499 { 5, 5, DIFF_HARD
, 6 },
500 { 5, 5, DIFF_HARD
, 7 },
501 { 3, 3, DIFF_HARD
, 8 },
502 { 3, 3, DIFF_HARD
, 9 },
503 { 3, 3, DIFF_HARD
, 10 },
504 { 6, 6, DIFF_HARD
, 11 },
505 { 6, 6, DIFF_HARD
, 12 },
507 { 7, 7, DIFF_EASY
, 0 },
508 { 10, 10, DIFF_EASY
, 0 },
509 { 7, 7, DIFF_NORMAL
, 0 },
510 { 10, 10, DIFF_NORMAL
, 0 },
511 { 7, 7, DIFF_HARD
, 0 },
512 { 10, 10, DIFF_HARD
, 0 },
513 { 10, 10, DIFF_HARD
, 1 },
514 { 12, 10, DIFF_HARD
, 2 },
515 { 7, 7, DIFF_HARD
, 3 },
516 { 9, 9, DIFF_HARD
, 4 },
517 { 5, 4, DIFF_HARD
, 5 },
518 { 7, 7, DIFF_HARD
, 6 },
519 { 5, 5, DIFF_HARD
, 7 },
520 { 5, 5, DIFF_HARD
, 8 },
521 { 5, 4, DIFF_HARD
, 9 },
522 { 5, 4, DIFF_HARD
, 10 },
523 { 10, 10, DIFF_HARD
, 11 },
524 { 10, 10, DIFF_HARD
, 12 }
528 static int game_fetch_preset(int i
, char **name
, game_params
**params
)
533 if (i
< 0 || i
>= lenof(presets
))
536 tmppar
= snew(game_params
);
537 *tmppar
= presets
[i
];
539 sprintf(buf
, "%dx%d %s - %s", tmppar
->h
, tmppar
->w
,
540 gridnames
[tmppar
->type
], diffnames
[tmppar
->diff
]);
546 static void free_params(game_params
*params
)
551 static void decode_params(game_params
*params
, char const *string
)
553 params
->h
= params
->w
= atoi(string
);
554 params
->diff
= DIFF_EASY
;
555 while (*string
&& isdigit((unsigned char)*string
)) string
++;
556 if (*string
== 'x') {
558 params
->h
= atoi(string
);
559 while (*string
&& isdigit((unsigned char)*string
)) string
++;
561 if (*string
== 't') {
563 params
->type
= atoi(string
);
564 while (*string
&& isdigit((unsigned char)*string
)) string
++;
566 if (*string
== 'd') {
569 for (i
= 0; i
< DIFF_MAX
; i
++)
570 if (*string
== diffchars
[i
])
572 if (*string
) string
++;
576 static char *encode_params(game_params
*params
, int full
)
579 sprintf(str
, "%dx%dt%d", params
->w
, params
->h
, params
->type
);
581 sprintf(str
+ strlen(str
), "d%c", diffchars
[params
->diff
]);
585 static config_item
*game_configure(game_params
*params
)
590 ret
= snewn(5, config_item
);
592 ret
[0].name
= "Width";
593 ret
[0].type
= C_STRING
;
594 sprintf(buf
, "%d", params
->w
);
595 ret
[0].sval
= dupstr(buf
);
598 ret
[1].name
= "Height";
599 ret
[1].type
= C_STRING
;
600 sprintf(buf
, "%d", params
->h
);
601 ret
[1].sval
= dupstr(buf
);
604 ret
[2].name
= "Grid type";
605 ret
[2].type
= C_CHOICES
;
606 ret
[2].sval
= GRID_CONFIGS
;
607 ret
[2].ival
= params
->type
;
609 ret
[3].name
= "Difficulty";
610 ret
[3].type
= C_CHOICES
;
611 ret
[3].sval
= DIFFCONFIG
;
612 ret
[3].ival
= params
->diff
;
622 static game_params
*custom_params(config_item
*cfg
)
624 game_params
*ret
= snew(game_params
);
626 ret
->w
= atoi(cfg
[0].sval
);
627 ret
->h
= atoi(cfg
[1].sval
);
628 ret
->type
= cfg
[2].ival
;
629 ret
->diff
= cfg
[3].ival
;
634 static char *validate_params(game_params
*params
, int full
)
636 if (params
->type
< 0 || params
->type
>= NUM_GRID_TYPES
)
637 return "Illegal grid type";
638 if (params
->w
< grid_size_limits
[params
->type
].amin
||
639 params
->h
< grid_size_limits
[params
->type
].amin
)
640 return grid_size_limits
[params
->type
].aerr
;
641 if (params
->w
< grid_size_limits
[params
->type
].omin
&&
642 params
->h
< grid_size_limits
[params
->type
].omin
)
643 return grid_size_limits
[params
->type
].oerr
;
646 * This shouldn't be able to happen at all, since decode_params
647 * and custom_params will never generate anything that isn't
650 assert(params
->diff
< DIFF_MAX
);
655 /* Returns a newly allocated string describing the current puzzle */
656 static char *state_to_text(const game_state
*state
)
658 grid
*g
= state
->game_grid
;
660 int num_faces
= g
->num_faces
;
661 char *description
= snewn(num_faces
+ 1, char);
662 char *dp
= description
;
666 for (i
= 0; i
< num_faces
; i
++) {
667 if (state
->clues
[i
] < 0) {
668 if (empty_count
> 25) {
669 dp
+= sprintf(dp
, "%c", (int)(empty_count
+ 'a' - 1));
675 dp
+= sprintf(dp
, "%c", (int)(empty_count
+ 'a' - 1));
678 dp
+= sprintf(dp
, "%c", (int)CLUE2CHAR(state
->clues
[i
]));
683 dp
+= sprintf(dp
, "%c", (int)(empty_count
+ 'a' - 1));
685 retval
= dupstr(description
);
691 #define GRID_DESC_SEP '_'
693 /* Splits up a (optional) grid_desc from the game desc. Returns the
694 * grid_desc (which needs freeing) and updates the desc pointer to
695 * start of real desc, or returns NULL if no desc. */
696 static char *extract_grid_desc(char **desc
)
698 char *sep
= strchr(*desc
, GRID_DESC_SEP
), *gd
;
701 if (!sep
) return NULL
;
703 gd_len
= sep
- (*desc
);
704 gd
= snewn(gd_len
+1, char);
705 memcpy(gd
, *desc
, gd_len
);
713 /* We require that the params pass the test in validate_params and that the
714 * description fills the entire game area */
715 static char *validate_desc(game_params
*params
, char *desc
)
719 char *grid_desc
, *ret
;
721 /* It's pretty inefficient to do this just for validation. All we need to
722 * know is the precise number of faces. */
723 grid_desc
= extract_grid_desc(&desc
);
724 ret
= grid_validate_desc(grid_types
[params
->type
], params
->w
, params
->h
, grid_desc
);
727 g
= loopy_generate_grid(params
, grid_desc
);
728 if (grid_desc
) sfree(grid_desc
);
730 for (; *desc
; ++desc
) {
731 if ((*desc
>= '0' && *desc
<= '9') || (*desc
>= 'A' && *desc
<= 'Z')) {
736 count
+= *desc
- 'a' + 1;
739 return "Unknown character in description";
742 if (count
< g
->num_faces
)
743 return "Description too short for board size";
744 if (count
> g
->num_faces
)
745 return "Description too long for board size";
752 /* Sums the lengths of the numbers in range [0,n) */
753 /* See equivalent function in solo.c for justification of this. */
754 static int len_0_to_n(int n
)
756 int len
= 1; /* Counting 0 as a bit of a special case */
759 for (i
= 1; i
< n
; i
*= 10) {
760 len
+= max(n
- i
, 0);
766 static char *encode_solve_move(const game_state
*state
)
771 int num_edges
= state
->game_grid
->num_edges
;
773 /* This is going to return a string representing the moves needed to set
774 * every line in a grid to be the same as the ones in 'state'. The exact
775 * length of this string is predictable. */
777 len
= 1; /* Count the 'S' prefix */
778 /* Numbers in all lines */
779 len
+= len_0_to_n(num_edges
);
780 /* For each line we also have a letter */
783 ret
= snewn(len
+ 1, char);
786 p
+= sprintf(p
, "S");
788 for (i
= 0; i
< num_edges
; i
++) {
789 switch (state
->lines
[i
]) {
791 p
+= sprintf(p
, "%dy", i
);
794 p
+= sprintf(p
, "%dn", i
);
799 /* No point in doing sums like that if they're going to be wrong */
800 assert(strlen(ret
) <= (size_t)len
);
804 static game_ui
*new_ui(game_state
*state
)
809 static void free_ui(game_ui
*ui
)
813 static char *encode_ui(game_ui
*ui
)
818 static void decode_ui(game_ui
*ui
, char *encoding
)
822 static void game_changed_state(game_ui
*ui
, game_state
*oldstate
,
823 game_state
*newstate
)
827 static void game_compute_size(game_params
*params
, int tilesize
,
830 int grid_width
, grid_height
, rendered_width
, rendered_height
;
833 grid_compute_size(grid_types
[params
->type
], params
->w
, params
->h
,
834 &g_tilesize
, &grid_width
, &grid_height
);
836 /* multiply first to minimise rounding error on integer division */
837 rendered_width
= grid_width
* tilesize
/ g_tilesize
;
838 rendered_height
= grid_height
* tilesize
/ g_tilesize
;
839 *x
= rendered_width
+ 2 * BORDER(tilesize
) + 1;
840 *y
= rendered_height
+ 2 * BORDER(tilesize
) + 1;
843 static void game_set_size(drawing
*dr
, game_drawstate
*ds
,
844 game_params
*params
, int tilesize
)
846 ds
->tilesize
= tilesize
;
849 static float *game_colours(frontend
*fe
, int *ncolours
)
851 float *ret
= snewn(4 * NCOLOURS
, float);
853 frontend_default_colour(fe
, &ret
[COL_BACKGROUND
* 3]);
855 ret
[COL_FOREGROUND
* 3 + 0] = 0.0F
;
856 ret
[COL_FOREGROUND
* 3 + 1] = 0.0F
;
857 ret
[COL_FOREGROUND
* 3 + 2] = 0.0F
;
860 * We want COL_LINEUNKNOWN to be a yellow which is a bit darker
861 * than the background. (I previously set it to 0.8,0.8,0, but
862 * found that this went badly with the 0.8,0.8,0.8 favoured as a
863 * background by the Java frontend.)
865 ret
[COL_LINEUNKNOWN
* 3 + 0] = ret
[COL_BACKGROUND
* 3 + 0] * 0.9F
;
866 ret
[COL_LINEUNKNOWN
* 3 + 1] = ret
[COL_BACKGROUND
* 3 + 1] * 0.9F
;
867 ret
[COL_LINEUNKNOWN
* 3 + 2] = 0.0F
;
869 ret
[COL_HIGHLIGHT
* 3 + 0] = 1.0F
;
870 ret
[COL_HIGHLIGHT
* 3 + 1] = 1.0F
;
871 ret
[COL_HIGHLIGHT
* 3 + 2] = 1.0F
;
873 ret
[COL_MISTAKE
* 3 + 0] = 1.0F
;
874 ret
[COL_MISTAKE
* 3 + 1] = 0.0F
;
875 ret
[COL_MISTAKE
* 3 + 2] = 0.0F
;
877 ret
[COL_SATISFIED
* 3 + 0] = 0.0F
;
878 ret
[COL_SATISFIED
* 3 + 1] = 0.0F
;
879 ret
[COL_SATISFIED
* 3 + 2] = 0.0F
;
881 /* We want the faint lines to be a bit darker than the background.
882 * Except if the background is pretty dark already; then it ought to be a
883 * bit lighter. Oy vey.
885 ret
[COL_FAINT
* 3 + 0] = ret
[COL_BACKGROUND
* 3 + 0] * 0.9F
;
886 ret
[COL_FAINT
* 3 + 1] = ret
[COL_BACKGROUND
* 3 + 1] * 0.9F
;
887 ret
[COL_FAINT
* 3 + 2] = ret
[COL_BACKGROUND
* 3 + 2] * 0.9F
;
889 *ncolours
= NCOLOURS
;
893 static game_drawstate
*game_new_drawstate(drawing
*dr
, game_state
*state
)
895 struct game_drawstate
*ds
= snew(struct game_drawstate
);
896 int num_faces
= state
->game_grid
->num_faces
;
897 int num_edges
= state
->game_grid
->num_edges
;
902 ds
->lines
= snewn(num_edges
, char);
903 ds
->clue_error
= snewn(num_faces
, char);
904 ds
->clue_satisfied
= snewn(num_faces
, char);
905 ds
->textx
= snewn(num_faces
, int);
906 ds
->texty
= snewn(num_faces
, int);
909 memset(ds
->lines
, LINE_UNKNOWN
, num_edges
);
910 memset(ds
->clue_error
, 0, num_faces
);
911 memset(ds
->clue_satisfied
, 0, num_faces
);
912 for (i
= 0; i
< num_faces
; i
++)
913 ds
->textx
[i
] = ds
->texty
[i
] = -1;
918 static void game_free_drawstate(drawing
*dr
, game_drawstate
*ds
)
922 sfree(ds
->clue_error
);
923 sfree(ds
->clue_satisfied
);
928 static int game_timing_state(game_state
*state
, game_ui
*ui
)
933 static float game_anim_length(game_state
*oldstate
, game_state
*newstate
,
934 int dir
, game_ui
*ui
)
939 static int game_can_format_as_text_now(game_params
*params
)
941 if (params
->type
!= 0)
946 static char *game_text_format(game_state
*state
)
952 grid
*g
= state
->game_grid
;
955 assert(state
->grid_type
== 0);
957 /* Work out the basic size unit */
958 f
= g
->faces
; /* first face */
959 assert(f
->order
== 4);
960 /* The dots are ordered clockwise, so the two opposite
961 * corners are guaranteed to span the square */
962 cell_size
= abs(f
->dots
[0]->x
- f
->dots
[2]->x
);
964 w
= (g
->highest_x
- g
->lowest_x
) / cell_size
;
965 h
= (g
->highest_y
- g
->lowest_y
) / cell_size
;
967 /* Create a blank "canvas" to "draw" on */
970 ret
= snewn(W
* H
+ 1, char);
971 for (y
= 0; y
< H
; y
++) {
972 for (x
= 0; x
< W
-1; x
++) {
975 ret
[y
*W
+ W
-1] = '\n';
979 /* Fill in edge info */
980 for (i
= 0; i
< g
->num_edges
; i
++) {
981 grid_edge
*e
= g
->edges
+ i
;
982 /* Cell coordinates, from (0,0) to (w-1,h-1) */
983 int x1
= (e
->dot1
->x
- g
->lowest_x
) / cell_size
;
984 int x2
= (e
->dot2
->x
- g
->lowest_x
) / cell_size
;
985 int y1
= (e
->dot1
->y
- g
->lowest_y
) / cell_size
;
986 int y2
= (e
->dot2
->y
- g
->lowest_y
) / cell_size
;
987 /* Midpoint, in canvas coordinates (canvas coordinates are just twice
988 * cell coordinates) */
991 switch (state
->lines
[i
]) {
993 ret
[y
*W
+ x
] = (y1
== y2
) ?
'-' : '|';
999 break; /* already a space */
1001 assert(!"Illegal line state");
1006 for (i
= 0; i
< g
->num_faces
; i
++) {
1010 assert(f
->order
== 4);
1011 /* Cell coordinates, from (0,0) to (w-1,h-1) */
1012 x1
= (f
->dots
[0]->x
- g
->lowest_x
) / cell_size
;
1013 x2
= (f
->dots
[2]->x
- g
->lowest_x
) / cell_size
;
1014 y1
= (f
->dots
[0]->y
- g
->lowest_y
) / cell_size
;
1015 y2
= (f
->dots
[2]->y
- g
->lowest_y
) / cell_size
;
1016 /* Midpoint, in canvas coordinates */
1019 ret
[y
*W
+ x
] = CLUE2CHAR(state
->clues
[i
]);
1024 /* ----------------------------------------------------------------------
1029 static void check_caches(const solver_state
* sstate
)
1032 const game_state
*state
= sstate
->state
;
1033 const grid
*g
= state
->game_grid
;
1035 for (i
= 0; i
< g
->num_dots
; i
++) {
1036 assert(dot_order(state
, i
, LINE_YES
) == sstate
->dot_yes_count
[i
]);
1037 assert(dot_order(state
, i
, LINE_NO
) == sstate
->dot_no_count
[i
]);
1040 for (i
= 0; i
< g
->num_faces
; i
++) {
1041 assert(face_order(state
, i
, LINE_YES
) == sstate
->face_yes_count
[i
]);
1042 assert(face_order(state
, i
, LINE_NO
) == sstate
->face_no_count
[i
]);
1047 #define check_caches(s) \
1049 fprintf(stderr, "check_caches at line %d\n", __LINE__); \
1053 #endif /* DEBUG_CACHES */
1055 /* ----------------------------------------------------------------------
1056 * Solver utility functions
1059 /* Sets the line (with index i) to the new state 'line_new', and updates
1060 * the cached counts of any affected faces and dots.
1061 * Returns TRUE if this actually changed the line's state. */
1062 static int solver_set_line(solver_state
*sstate
, int i
,
1063 enum line_state line_new
1065 , const char *reason
1069 game_state
*state
= sstate
->state
;
1073 assert(line_new
!= LINE_UNKNOWN
);
1075 check_caches(sstate
);
1077 if (state
->lines
[i
] == line_new
) {
1078 return FALSE
; /* nothing changed */
1080 state
->lines
[i
] = line_new
;
1083 fprintf(stderr
, "solver: set line [%d] to %s (%s)\n",
1084 i
, line_new
== LINE_YES ?
"YES" : "NO",
1088 g
= state
->game_grid
;
1091 /* Update the cache for both dots and both faces affected by this. */
1092 if (line_new
== LINE_YES
) {
1093 sstate
->dot_yes_count
[e
->dot1
- g
->dots
]++;
1094 sstate
->dot_yes_count
[e
->dot2
- g
->dots
]++;
1096 sstate
->face_yes_count
[e
->face1
- g
->faces
]++;
1099 sstate
->face_yes_count
[e
->face2
- g
->faces
]++;
1102 sstate
->dot_no_count
[e
->dot1
- g
->dots
]++;
1103 sstate
->dot_no_count
[e
->dot2
- g
->dots
]++;
1105 sstate
->face_no_count
[e
->face1
- g
->faces
]++;
1108 sstate
->face_no_count
[e
->face2
- g
->faces
]++;
1112 check_caches(sstate
);
1117 #define solver_set_line(a, b, c) \
1118 solver_set_line(a, b, c, __FUNCTION__)
1122 * Merge two dots due to the existence of an edge between them.
1123 * Updates the dsf tracking equivalence classes, and keeps track of
1124 * the length of path each dot is currently a part of.
1125 * Returns TRUE if the dots were already linked, ie if they are part of a
1126 * closed loop, and false otherwise.
1128 static int merge_dots(solver_state
*sstate
, int edge_index
)
1131 grid
*g
= sstate
->state
->game_grid
;
1132 grid_edge
*e
= g
->edges
+ edge_index
;
1134 i
= e
->dot1
- g
->dots
;
1135 j
= e
->dot2
- g
->dots
;
1137 i
= dsf_canonify(sstate
->dotdsf
, i
);
1138 j
= dsf_canonify(sstate
->dotdsf
, j
);
1143 len
= sstate
->looplen
[i
] + sstate
->looplen
[j
];
1144 dsf_merge(sstate
->dotdsf
, i
, j
);
1145 i
= dsf_canonify(sstate
->dotdsf
, i
);
1146 sstate
->looplen
[i
] = len
;
1151 /* Merge two lines because the solver has deduced that they must be either
1152 * identical or opposite. Returns TRUE if this is new information, otherwise
1154 static int merge_lines(solver_state
*sstate
, int i
, int j
, int inverse
1156 , const char *reason
1162 assert(i
< sstate
->state
->game_grid
->num_edges
);
1163 assert(j
< sstate
->state
->game_grid
->num_edges
);
1165 i
= edsf_canonify(sstate
->linedsf
, i
, &inv_tmp
);
1167 j
= edsf_canonify(sstate
->linedsf
, j
, &inv_tmp
);
1170 edsf_merge(sstate
->linedsf
, i
, j
, inverse
);
1174 fprintf(stderr
, "%s [%d] [%d] %s(%s)\n",
1176 inverse ?
"inverse " : "", reason
);
1183 #define merge_lines(a, b, c, d) \
1184 merge_lines(a, b, c, d, __FUNCTION__)
1187 /* Count the number of lines of a particular type currently going into the
1189 static int dot_order(const game_state
* state
, int dot
, char line_type
)
1192 grid
*g
= state
->game_grid
;
1193 grid_dot
*d
= g
->dots
+ dot
;
1196 for (i
= 0; i
< d
->order
; i
++) {
1197 grid_edge
*e
= d
->edges
[i
];
1198 if (state
->lines
[e
- g
->edges
] == line_type
)
1204 /* Count the number of lines of a particular type currently surrounding the
1206 static int face_order(const game_state
* state
, int face
, char line_type
)
1209 grid
*g
= state
->game_grid
;
1210 grid_face
*f
= g
->faces
+ face
;
1213 for (i
= 0; i
< f
->order
; i
++) {
1214 grid_edge
*e
= f
->edges
[i
];
1215 if (state
->lines
[e
- g
->edges
] == line_type
)
1221 /* Set all lines bordering a dot of type old_type to type new_type
1222 * Return value tells caller whether this function actually did anything */
1223 static int dot_setall(solver_state
*sstate
, int dot
,
1224 char old_type
, char new_type
)
1226 int retval
= FALSE
, r
;
1227 game_state
*state
= sstate
->state
;
1232 if (old_type
== new_type
)
1235 g
= state
->game_grid
;
1238 for (i
= 0; i
< d
->order
; i
++) {
1239 int line_index
= d
->edges
[i
] - g
->edges
;
1240 if (state
->lines
[line_index
] == old_type
) {
1241 r
= solver_set_line(sstate
, line_index
, new_type
);
1249 /* Set all lines bordering a face of type old_type to type new_type */
1250 static int face_setall(solver_state
*sstate
, int face
,
1251 char old_type
, char new_type
)
1253 int retval
= FALSE
, r
;
1254 game_state
*state
= sstate
->state
;
1259 if (old_type
== new_type
)
1262 g
= state
->game_grid
;
1263 f
= g
->faces
+ face
;
1265 for (i
= 0; i
< f
->order
; i
++) {
1266 int line_index
= f
->edges
[i
] - g
->edges
;
1267 if (state
->lines
[line_index
] == old_type
) {
1268 r
= solver_set_line(sstate
, line_index
, new_type
);
1276 /* ----------------------------------------------------------------------
1277 * Loop generation and clue removal
1280 /* We're going to store lists of current candidate faces for colouring black
1282 * Each face gets a 'score', which tells us how adding that face right
1283 * now would affect the curliness of the solution loop. We're trying to
1284 * maximise that quantity so will bias our random selection of faces to
1285 * colour those with high scores */
1289 unsigned long random
;
1290 /* No need to store a grid_face* here. The 'face_scores' array will
1291 * be a list of 'face_score' objects, one for each face of the grid, so
1292 * the position (index) within the 'face_scores' array will determine
1293 * which face corresponds to a particular face_score.
1294 * Having a single 'face_scores' array for all faces simplifies memory
1295 * management, and probably improves performance, because we don't have to
1296 * malloc/free each individual face_score, and we don't have to maintain
1297 * a mapping from grid_face* pointers to face_score* pointers.
1301 static int generic_sort_cmpfn(void *v1
, void *v2
, size_t offset
)
1303 struct face_score
*f1
= v1
;
1304 struct face_score
*f2
= v2
;
1307 r
= *(int *)((char *)f2
+ offset
) - *(int *)((char *)f1
+ offset
);
1312 if (f1
->random
< f2
->random
)
1314 else if (f1
->random
> f2
->random
)
1318 * It's _just_ possible that two faces might have been given
1319 * the same random value. In that situation, fall back to
1320 * comparing based on the positions within the face_scores list.
1321 * This introduces a tiny directional bias, but not a significant one.
1326 static int white_sort_cmpfn(void *v1
, void *v2
)
1328 return generic_sort_cmpfn(v1
, v2
, offsetof(struct face_score
,white_score
));
1331 static int black_sort_cmpfn(void *v1
, void *v2
)
1333 return generic_sort_cmpfn(v1
, v2
, offsetof(struct face_score
,black_score
));
1336 enum face_colour
{ FACE_WHITE
, FACE_GREY
, FACE_BLACK
};
1338 /* face should be of type grid_face* here. */
1339 #define FACE_COLOUR(face) \
1340 ( (face) == NULL ? FACE_BLACK : \
1341 board[(face) - g->faces] )
1343 /* 'board' is an array of these enums, indicating which faces are
1344 * currently black/white/grey. 'colour' is FACE_WHITE or FACE_BLACK.
1345 * Returns whether it's legal to colour the given face with this colour. */
1346 static int can_colour_face(grid
*g
, char* board
, int face_index
,
1347 enum face_colour colour
)
1350 grid_face
*test_face
= g
->faces
+ face_index
;
1351 grid_face
*starting_face
, *current_face
;
1352 grid_dot
*starting_dot
;
1354 int current_state
, s
; /* booleans: equal or not-equal to 'colour' */
1355 int found_same_coloured_neighbour
= FALSE
;
1356 assert(board
[face_index
] != colour
);
1358 /* Can only consider a face for colouring if it's adjacent to a face
1359 * with the same colour. */
1360 for (i
= 0; i
< test_face
->order
; i
++) {
1361 grid_edge
*e
= test_face
->edges
[i
];
1362 grid_face
*f
= (e
->face1
== test_face
) ? e
->face2
: e
->face1
;
1363 if (FACE_COLOUR(f
) == colour
) {
1364 found_same_coloured_neighbour
= TRUE
;
1368 if (!found_same_coloured_neighbour
)
1371 /* Need to avoid creating a loop of faces of this colour around some
1372 * differently-coloured faces.
1373 * Also need to avoid meeting a same-coloured face at a corner, with
1374 * other-coloured faces in between. Here's a simple test that (I believe)
1375 * takes care of both these conditions:
1377 * Take the circular path formed by this face's edges, and inflate it
1378 * slightly outwards. Imagine walking around this path and consider
1379 * the faces that you visit in sequence. This will include all faces
1380 * touching the given face, either along an edge or just at a corner.
1381 * Count the number of 'colour'/not-'colour' transitions you encounter, as
1382 * you walk along the complete loop. This will obviously turn out to be
1384 * If 0, we're either in the middle of an "island" of this colour (should
1385 * be impossible as we're not supposed to create black or white loops),
1386 * or we're about to start a new island - also not allowed.
1387 * If 4 or greater, there are too many separate coloured regions touching
1388 * this face, and colouring it would create a loop or a corner-violation.
1389 * The only allowed case is when the count is exactly 2. */
1391 /* i points to a dot around the test face.
1392 * j points to a face around the i^th dot.
1393 * The current face will always be:
1394 * test_face->dots[i]->faces[j]
1395 * We assume dots go clockwise around the test face,
1396 * and faces go clockwise around dots. */
1399 * The end condition is slightly fiddly. In sufficiently strange
1400 * degenerate grids, our test face may be adjacent to the same
1401 * other face multiple times (typically if it's the exterior
1402 * face). Consider this, in particular:
1410 * The bottom left face there is adjacent to the exterior face
1411 * twice, so we can't just terminate our iteration when we reach
1412 * the same _face_ we started at. Furthermore, we can't
1413 * condition on having the same (i,j) pair either, because
1414 * several (i,j) pairs identify the bottom left contiguity with
1415 * the exterior face! We canonicalise the (i,j) pair by taking
1416 * one step around before we set the termination tracking.
1420 current_face
= test_face
->dots
[0]->faces
[0];
1421 if (current_face
== test_face
) {
1423 current_face
= test_face
->dots
[0]->faces
[1];
1426 current_state
= (FACE_COLOUR(current_face
) == colour
);
1427 starting_dot
= NULL
;
1428 starting_face
= NULL
;
1430 /* Advance to next face.
1431 * Need to loop here because it might take several goes to
1435 if (j
== test_face
->dots
[i
]->order
)
1438 if (test_face
->dots
[i
]->faces
[j
] == test_face
) {
1439 /* Advance to next dot round test_face, then
1440 * find current_face around new dot
1441 * and advance to the next face clockwise */
1443 if (i
== test_face
->order
)
1445 for (j
= 0; j
< test_face
->dots
[i
]->order
; j
++) {
1446 if (test_face
->dots
[i
]->faces
[j
] == current_face
)
1449 /* Must actually find current_face around new dot,
1450 * or else something's wrong with the grid. */
1451 assert(j
!= test_face
->dots
[i
]->order
);
1452 /* Found, so advance to next face and try again */
1457 /* (i,j) are now advanced to next face */
1458 current_face
= test_face
->dots
[i
]->faces
[j
];
1459 s
= (FACE_COLOUR(current_face
) == colour
);
1460 if (!starting_dot
) {
1461 starting_dot
= test_face
->dots
[i
];
1462 starting_face
= current_face
;
1465 if (s
!= current_state
) {
1468 if (transitions
> 2)
1471 if (test_face
->dots
[i
] == starting_dot
&&
1472 current_face
== starting_face
)
1477 return (transitions
== 2) ? TRUE
: FALSE
;
1480 /* Count the number of neighbours of 'face', having colour 'colour' */
1481 static int face_num_neighbours(grid
*g
, char *board
, grid_face
*face
,
1482 enum face_colour colour
)
1484 int colour_count
= 0;
1488 for (i
= 0; i
< face
->order
; i
++) {
1490 f
= (e
->face1
== face
) ? e
->face2
: e
->face1
;
1491 if (FACE_COLOUR(f
) == colour
)
1494 return colour_count
;
1497 /* The 'score' of a face reflects its current desirability for selection
1498 * as the next face to colour white or black. We want to encourage moving
1499 * into grey areas and increasing loopiness, so we give scores according to
1500 * how many of the face's neighbours are currently coloured the same as the
1501 * proposed colour. */
1502 static int face_score(grid
*g
, char *board
, grid_face
*face
,
1503 enum face_colour colour
)
1505 /* Simple formula: score = 0 - num. same-coloured neighbours,
1506 * so a higher score means fewer same-coloured neighbours. */
1507 return -face_num_neighbours(g
, board
, face
, colour
);
1510 /* Generate a new complete set of clues for the given game_state.
1511 * The method is to generate a WHITE/BLACK colouring of all the faces,
1512 * such that the WHITE faces will define the inside of the path, and the
1513 * BLACK faces define the outside.
1514 * To do this, we initially colour all faces GREY. The infinite space outside
1515 * the grid is coloured BLACK, and we choose a random face to colour WHITE.
1516 * Then we gradually grow the BLACK and the WHITE regions, eliminating GREY
1517 * faces, until the grid is filled with BLACK/WHITE. As we grow the regions,
1518 * we avoid creating loops of a single colour, to preserve the topological
1519 * shape of the WHITE and BLACK regions.
1520 * We also try to make the boundary as loopy and twisty as possible, to avoid
1521 * generating paths that are uninteresting.
1522 * The algorithm works by choosing a BLACK/WHITE colour, then choosing a GREY
1523 * face that can be coloured with that colour (without violating the
1524 * topological shape of that region). It's not obvious, but I think this
1525 * algorithm is guaranteed to terminate without leaving any GREY faces behind.
1526 * Indeed, if there are any GREY faces at all, both the WHITE and BLACK
1527 * regions can be grown.
1528 * This is checked using assert()ions, and I haven't seen any failures yet.
1530 * Hand-wavy proof: imagine what can go wrong...
1532 * Could the white faces get completely cut off by the black faces, and still
1533 * leave some grey faces remaining?
1534 * No, because then the black faces would form a loop around both the white
1535 * faces and the grey faces, which is disallowed because we continually
1536 * maintain the correct topological shape of the black region.
1537 * Similarly, the black faces can never get cut off by the white faces. That
1538 * means both the WHITE and BLACK regions always have some room to grow into
1540 * Could it be that we can't colour some GREY face, because there are too many
1541 * WHITE/BLACK transitions as we walk round the face? (see the
1542 * can_colour_face() function for details)
1543 * No. Imagine otherwise, and we see WHITE/BLACK/WHITE/BLACK as we walk
1544 * around the face. The two WHITE faces would be connected by a WHITE path,
1545 * and the BLACK faces would be connected by a BLACK path. These paths would
1546 * have to cross, which is impossible.
1547 * Another thing that could go wrong: perhaps we can't find any GREY face to
1548 * colour WHITE, because it would create a loop-violation or a corner-violation
1549 * with the other WHITE faces?
1550 * This is a little bit tricky to prove impossible. Imagine you have such a
1551 * GREY face (that is, if you coloured it WHITE, you would create a WHITE loop
1552 * or corner violation).
1553 * That would cut all the non-white area into two blobs. One of those blobs
1554 * must be free of BLACK faces (because the BLACK stuff is a connected blob).
1555 * So we have a connected GREY area, completely surrounded by WHITE
1556 * (including the GREY face we've tentatively coloured WHITE).
1557 * A well-known result in graph theory says that you can always find a GREY
1558 * face whose removal leaves the remaining GREY area connected. And it says
1559 * there are at least two such faces, so we can always choose the one that
1560 * isn't the "tentative" GREY face. Colouring that face WHITE leaves
1561 * everything nice and connected, including that "tentative" GREY face which
1562 * acts as a gateway to the rest of the non-WHITE grid.
1564 static void add_full_clues(game_state
*state
, random_state
*rs
)
1566 signed char *clues
= state
->clues
;
1568 grid
*g
= state
->game_grid
;
1570 int num_faces
= g
->num_faces
;
1571 struct face_score
*face_scores
; /* Array of face_score objects */
1572 struct face_score
*fs
; /* Points somewhere in the above list */
1573 struct grid_face
*cur_face
;
1574 tree234
*lightable_faces_sorted
;
1575 tree234
*darkable_faces_sorted
;
1579 board
= snewn(num_faces
, char);
1582 memset(board
, FACE_GREY
, num_faces
);
1584 /* Create and initialise the list of face_scores */
1585 face_scores
= snewn(num_faces
, struct face_score
);
1586 for (i
= 0; i
< num_faces
; i
++) {
1587 face_scores
[i
].random
= random_bits(rs
, 31);
1588 face_scores
[i
].black_score
= face_scores
[i
].white_score
= 0;
1591 /* Colour a random, finite face white. The infinite face is implicitly
1592 * coloured black. Together, they will seed the random growth process
1593 * for the black and white areas. */
1594 i
= random_upto(rs
, num_faces
);
1595 board
[i
] = FACE_WHITE
;
1597 /* We need a way of favouring faces that will increase our loopiness.
1598 * We do this by maintaining a list of all candidate faces sorted by
1599 * their score and choose randomly from that with appropriate skew.
1600 * In order to avoid consistently biasing towards particular faces, we
1601 * need the sort order _within_ each group of scores to be completely
1602 * random. But it would be abusing the hospitality of the tree234 data
1603 * structure if our comparison function were nondeterministic :-). So with
1604 * each face we associate a random number that does not change during a
1605 * particular run of the generator, and use that as a secondary sort key.
1606 * Yes, this means we will be biased towards particular random faces in
1607 * any one run but that doesn't actually matter. */
1609 lightable_faces_sorted
= newtree234(white_sort_cmpfn
);
1610 darkable_faces_sorted
= newtree234(black_sort_cmpfn
);
1612 /* Initialise the lists of lightable and darkable faces. This is
1613 * slightly different from the code inside the while-loop, because we need
1614 * to check every face of the board (the grid structure does not keep a
1615 * list of the infinite face's neighbours). */
1616 for (i
= 0; i
< num_faces
; i
++) {
1617 grid_face
*f
= g
->faces
+ i
;
1618 struct face_score
*fs
= face_scores
+ i
;
1619 if (board
[i
] != FACE_GREY
) continue;
1620 /* We need the full colourability check here, it's not enough simply
1621 * to check neighbourhood. On some grids, a neighbour of the infinite
1622 * face is not necessarily darkable. */
1623 if (can_colour_face(g
, board
, i
, FACE_BLACK
)) {
1624 fs
->black_score
= face_score(g
, board
, f
, FACE_BLACK
);
1625 add234(darkable_faces_sorted
, fs
);
1627 if (can_colour_face(g
, board
, i
, FACE_WHITE
)) {
1628 fs
->white_score
= face_score(g
, board
, f
, FACE_WHITE
);
1629 add234(lightable_faces_sorted
, fs
);
1633 /* Colour faces one at a time until no more faces are colourable. */
1636 enum face_colour colour
;
1637 struct face_score
*fs_white
, *fs_black
;
1638 int c_lightable
= count234(lightable_faces_sorted
);
1639 int c_darkable
= count234(darkable_faces_sorted
);
1640 if (c_lightable
== 0 && c_darkable
== 0) {
1641 /* No more faces we can use at all. */
1644 assert(c_lightable
!= 0 && c_darkable
!= 0);
1646 fs_white
= (struct face_score
*)index234(lightable_faces_sorted
, 0);
1647 fs_black
= (struct face_score
*)index234(darkable_faces_sorted
, 0);
1649 /* Choose a colour, and colour the best available face
1650 * with that colour. */
1651 colour
= random_upto(rs
, 2) ? FACE_WHITE
: FACE_BLACK
;
1653 if (colour
== FACE_WHITE
)
1658 i
= fs
- face_scores
;
1659 assert(board
[i
] == FACE_GREY
);
1662 /* Remove this newly-coloured face from the lists. These lists should
1663 * only contain grey faces. */
1664 del234(lightable_faces_sorted
, fs
);
1665 del234(darkable_faces_sorted
, fs
);
1667 /* Remember which face we've just coloured */
1668 cur_face
= g
->faces
+ i
;
1670 /* The face we've just coloured potentially affects the colourability
1671 * and the scores of any neighbouring faces (touching at a corner or
1672 * edge). So the search needs to be conducted around all faces
1673 * touching the one we've just lit. Iterate over its corners, then
1674 * over each corner's faces. For each such face, we remove it from
1675 * the lists, recalculate any scores, then add it back to the lists
1676 * (depending on whether it is lightable, darkable or both). */
1677 for (i
= 0; i
< cur_face
->order
; i
++) {
1678 grid_dot
*d
= cur_face
->dots
[i
];
1679 for (j
= 0; j
< d
->order
; j
++) {
1680 grid_face
*f
= d
->faces
[j
];
1681 int fi
; /* face index of f */
1688 /* If the face is already coloured, it won't be on our
1689 * lightable/darkable lists anyway, so we can skip it without
1690 * bothering with the removal step. */
1691 if (FACE_COLOUR(f
) != FACE_GREY
) continue;
1693 /* Find the face index and face_score* corresponding to f */
1695 fs
= face_scores
+ fi
;
1697 /* Remove from lightable list if it's in there. We do this,
1698 * even if it is still lightable, because the score might
1699 * be different, and we need to remove-then-add to maintain
1700 * correct sort order. */
1701 del234(lightable_faces_sorted
, fs
);
1702 if (can_colour_face(g
, board
, fi
, FACE_WHITE
)) {
1703 fs
->white_score
= face_score(g
, board
, f
, FACE_WHITE
);
1704 add234(lightable_faces_sorted
, fs
);
1706 /* Do the same for darkable list. */
1707 del234(darkable_faces_sorted
, fs
);
1708 if (can_colour_face(g
, board
, fi
, FACE_BLACK
)) {
1709 fs
->black_score
= face_score(g
, board
, f
, FACE_BLACK
);
1710 add234(darkable_faces_sorted
, fs
);
1717 freetree234(lightable_faces_sorted
);
1718 freetree234(darkable_faces_sorted
);
1721 /* The next step requires a shuffled list of all faces */
1722 face_list
= snewn(num_faces
, int);
1723 for (i
= 0; i
< num_faces
; ++i
) {
1726 shuffle(face_list
, num_faces
, sizeof(int), rs
);
1728 /* The above loop-generation algorithm can often leave large clumps
1729 * of faces of one colour. In extreme cases, the resulting path can be
1730 * degenerate and not very satisfying to solve.
1731 * This next step alleviates this problem:
1732 * Go through the shuffled list, and flip the colour of any face we can
1733 * legally flip, and which is adjacent to only one face of the opposite
1734 * colour - this tends to grow 'tendrils' into any clumps.
1735 * Repeat until we can find no more faces to flip. This will
1736 * eventually terminate, because each flip increases the loop's
1737 * perimeter, which cannot increase for ever.
1738 * The resulting path will have maximal loopiness (in the sense that it
1739 * cannot be improved "locally". Unfortunately, this allows a player to
1740 * make some illicit deductions. To combat this (and make the path more
1741 * interesting), we do one final pass making random flips. */
1743 /* Set to TRUE for final pass */
1744 do_random_pass
= FALSE
;
1747 /* Remember whether a flip occurred during this pass */
1748 int flipped
= FALSE
;
1750 for (i
= 0; i
< num_faces
; ++i
) {
1751 int j
= face_list
[i
];
1752 enum face_colour opp
=
1753 (board
[j
] == FACE_WHITE
) ? FACE_BLACK
: FACE_WHITE
;
1754 if (can_colour_face(g
, board
, j
, opp
)) {
1755 grid_face
*face
= g
->faces
+j
;
1756 if (do_random_pass
) {
1757 /* final random pass */
1758 if (!random_upto(rs
, 10))
1761 /* normal pass - flip when neighbour count is 1 */
1762 if (face_num_neighbours(g
, board
, face
, opp
) == 1) {
1770 if (do_random_pass
) break;
1771 if (!flipped
) do_random_pass
= TRUE
;
1776 /* Fill out all the clues by initialising to 0, then iterating over
1777 * all edges and incrementing each clue as we find edges that border
1778 * between BLACK/WHITE faces. While we're at it, we verify that the
1779 * algorithm does work, and there aren't any GREY faces still there. */
1780 memset(clues
, 0, num_faces
);
1781 for (i
= 0; i
< g
->num_edges
; i
++) {
1782 grid_edge
*e
= g
->edges
+ i
;
1783 grid_face
*f1
= e
->face1
;
1784 grid_face
*f2
= e
->face2
;
1785 enum face_colour c1
= FACE_COLOUR(f1
);
1786 enum face_colour c2
= FACE_COLOUR(f2
);
1787 assert(c1
!= FACE_GREY
);
1788 assert(c2
!= FACE_GREY
);
1790 if (f1
) clues
[f1
- g
->faces
]++;
1791 if (f2
) clues
[f2
- g
->faces
]++;
1799 static int game_has_unique_soln(const game_state
*state
, int diff
)
1802 solver_state
*sstate_new
;
1803 solver_state
*sstate
= new_solver_state((game_state
*)state
, diff
);
1805 sstate_new
= solve_game_rec(sstate
);
1807 assert(sstate_new
->solver_status
!= SOLVER_MISTAKE
);
1808 ret
= (sstate_new
->solver_status
== SOLVER_SOLVED
);
1810 free_solver_state(sstate_new
);
1811 free_solver_state(sstate
);
1817 /* Remove clues one at a time at random. */
1818 static game_state
*remove_clues(game_state
*state
, random_state
*rs
,
1822 int num_faces
= state
->game_grid
->num_faces
;
1823 game_state
*ret
= dup_game(state
), *saved_ret
;
1826 /* We need to remove some clues. We'll do this by forming a list of all
1827 * available clues, shuffling it, then going along one at a
1828 * time clearing each clue in turn for which doing so doesn't render the
1829 * board unsolvable. */
1830 face_list
= snewn(num_faces
, int);
1831 for (n
= 0; n
< num_faces
; ++n
) {
1835 shuffle(face_list
, num_faces
, sizeof(int), rs
);
1837 for (n
= 0; n
< num_faces
; ++n
) {
1838 saved_ret
= dup_game(ret
);
1839 ret
->clues
[face_list
[n
]] = -1;
1841 if (game_has_unique_soln(ret
, diff
)) {
1842 free_game(saved_ret
);
1854 static char *new_game_desc(game_params
*params
, random_state
*rs
,
1855 char **aux
, int interactive
)
1857 /* solution and description both use run-length encoding in obvious ways */
1858 char *retval
, *game_desc
, *grid_desc
;
1860 game_state
*state
= snew(game_state
);
1861 game_state
*state_new
;
1863 grid_desc
= grid_new_desc(grid_types
[params
->type
], params
->w
, params
->h
, rs
);
1864 state
->game_grid
= g
= loopy_generate_grid(params
, grid_desc
);
1866 state
->clues
= snewn(g
->num_faces
, signed char);
1867 state
->lines
= snewn(g
->num_edges
, char);
1868 state
->line_errors
= snewn(g
->num_edges
, unsigned char);
1870 state
->grid_type
= params
->type
;
1874 memset(state
->lines
, LINE_UNKNOWN
, g
->num_edges
);
1875 memset(state
->line_errors
, 0, g
->num_edges
);
1877 state
->solved
= state
->cheated
= FALSE
;
1879 /* Get a new random solvable board with all its clues filled in. Yes, this
1880 * can loop for ever if the params are suitably unfavourable, but
1881 * preventing games smaller than 4x4 seems to stop this happening */
1883 add_full_clues(state
, rs
);
1884 } while (!game_has_unique_soln(state
, params
->diff
));
1886 state_new
= remove_clues(state
, rs
, params
->diff
);
1891 if (params
->diff
> 0 && game_has_unique_soln(state
, params
->diff
-1)) {
1893 fprintf(stderr
, "Rejecting board, it is too easy\n");
1895 goto newboard_please
;
1898 game_desc
= state_to_text(state
);
1903 retval
= snewn(strlen(grid_desc
) + 1 + strlen(game_desc
) + 1, char);
1904 sprintf(retval
, "%s%c%s", grid_desc
, (int)GRID_DESC_SEP
, game_desc
);
1911 assert(!validate_desc(params
, retval
));
1916 static game_state
*new_game(midend
*me
, game_params
*params
, char *desc
)
1919 game_state
*state
= snew(game_state
);
1920 int empties_to_make
= 0;
1925 int num_faces
, num_edges
;
1927 grid_desc
= extract_grid_desc(&desc
);
1928 state
->game_grid
= g
= loopy_generate_grid(params
, grid_desc
);
1929 if (grid_desc
) sfree(grid_desc
);
1933 num_faces
= g
->num_faces
;
1934 num_edges
= g
->num_edges
;
1936 state
->clues
= snewn(num_faces
, signed char);
1937 state
->lines
= snewn(num_edges
, char);
1938 state
->line_errors
= snewn(num_edges
, unsigned char);
1940 state
->solved
= state
->cheated
= FALSE
;
1942 state
->grid_type
= params
->type
;
1944 for (i
= 0; i
< num_faces
; i
++) {
1945 if (empties_to_make
) {
1947 state
->clues
[i
] = -1;
1953 n2
= *dp
- 'A' + 10;
1954 if (n
>= 0 && n
< 10) {
1955 state
->clues
[i
] = n
;
1956 } else if (n2
>= 10 && n2
< 36) {
1957 state
->clues
[i
] = n2
;
1961 state
->clues
[i
] = -1;
1962 empties_to_make
= n
- 1;
1967 memset(state
->lines
, LINE_UNKNOWN
, num_edges
);
1968 memset(state
->line_errors
, 0, num_edges
);
1972 /* Calculates the line_errors data, and checks if the current state is a
1974 static int check_completion(game_state
*state
)
1976 grid
*g
= state
->game_grid
;
1978 int num_faces
= g
->num_faces
;
1980 int infinite_area
, finite_area
;
1981 int loops_found
= 0;
1982 int found_edge_not_in_loop
= FALSE
;
1984 memset(state
->line_errors
, 0, g
->num_edges
);
1986 /* LL implementation of SGT's idea:
1987 * A loop will partition the grid into an inside and an outside.
1988 * If there is more than one loop, the grid will be partitioned into
1989 * even more distinct regions. We can therefore track equivalence of
1990 * faces, by saying that two faces are equivalent when there is a non-YES
1991 * edge between them.
1992 * We could keep track of the number of connected components, by counting
1993 * the number of dsf-merges that aren't no-ops.
1994 * But we're only interested in 3 separate cases:
1995 * no loops, one loop, more than one loop.
1997 * No loops: all faces are equivalent to the infinite face.
1998 * One loop: only two equivalence classes - finite and infinite.
1999 * >= 2 loops: there are 2 distinct finite regions.
2001 * So we simply make two passes through all the edges.
2002 * In the first pass, we dsf-merge the two faces bordering each non-YES
2004 * In the second pass, we look for YES-edges bordering:
2005 * a) two non-equivalent faces.
2006 * b) two non-equivalent faces, and one of them is part of a different
2007 * finite area from the first finite area we've seen.
2009 * An occurrence of a) means there is at least one loop.
2010 * An occurrence of b) means there is more than one loop.
2011 * Edges satisfying a) are marked as errors.
2013 * While we're at it, we set a flag if we find a YES edge that is not
2015 * This information will help decide, if there's a single loop, whether it
2016 * is a candidate for being a solution (that is, all YES edges are part of
2019 * If there is a candidate loop, we then go through all clues and check
2020 * they are all satisfied. If so, we have found a solution and we can
2021 * unmark all line_errors.
2024 /* Infinite face is at the end - its index is num_faces.
2025 * This macro is just to make this obvious! */
2026 #define INF_FACE num_faces
2027 dsf
= snewn(num_faces
+ 1, int);
2028 dsf_init(dsf
, num_faces
+ 1);
2031 for (i
= 0; i
< g
->num_edges
; i
++) {
2032 grid_edge
*e
= g
->edges
+ i
;
2033 int f1
= e
->face1 ? e
->face1
- g
->faces
: INF_FACE
;
2034 int f2
= e
->face2 ? e
->face2
- g
->faces
: INF_FACE
;
2035 if (state
->lines
[i
] != LINE_YES
)
2036 dsf_merge(dsf
, f1
, f2
);
2040 infinite_area
= dsf_canonify(dsf
, INF_FACE
);
2042 for (i
= 0; i
< g
->num_edges
; i
++) {
2043 grid_edge
*e
= g
->edges
+ i
;
2044 int f1
= e
->face1 ? e
->face1
- g
->faces
: INF_FACE
;
2045 int can1
= dsf_canonify(dsf
, f1
);
2046 int f2
= e
->face2 ? e
->face2
- g
->faces
: INF_FACE
;
2047 int can2
= dsf_canonify(dsf
, f2
);
2048 if (state
->lines
[i
] != LINE_YES
) continue;
2051 /* Faces are equivalent, so this edge not part of a loop */
2052 found_edge_not_in_loop
= TRUE
;
2055 state
->line_errors
[i
] = TRUE
;
2056 if (loops_found
== 0) loops_found
= 1;
2058 /* Don't bother with further checks if we've already found 2 loops */
2059 if (loops_found
== 2) continue;
2061 if (finite_area
== -1) {
2062 /* Found our first finite area */
2063 if (can1
!= infinite_area
)
2069 /* Have we found a second area? */
2070 if (finite_area
!= -1) {
2071 if (can1
!= infinite_area
&& can1
!= finite_area
) {
2075 if (can2
!= infinite_area
&& can2
!= finite_area
) {
2082 printf("loops_found = %d\n", loops_found);
2083 printf("found_edge_not_in_loop = %s\n",
2084 found_edge_not_in_loop ? "TRUE" : "FALSE");
2087 sfree(dsf
); /* No longer need the dsf */
2089 /* Have we found a candidate loop? */
2090 if (loops_found
== 1 && !found_edge_not_in_loop
) {
2091 /* Yes, so check all clues are satisfied */
2092 int found_clue_violation
= FALSE
;
2093 for (i
= 0; i
< num_faces
; i
++) {
2094 int c
= state
->clues
[i
];
2096 if (face_order(state
, i
, LINE_YES
) != c
) {
2097 found_clue_violation
= TRUE
;
2103 if (!found_clue_violation
) {
2104 /* The loop is good */
2105 memset(state
->line_errors
, 0, g
->num_edges
);
2106 return TRUE
; /* No need to bother checking for dot violations */
2110 /* Check for dot violations */
2111 for (i
= 0; i
< g
->num_dots
; i
++) {
2112 int yes
= dot_order(state
, i
, LINE_YES
);
2113 int unknown
= dot_order(state
, i
, LINE_UNKNOWN
);
2114 if ((yes
== 1 && unknown
== 0) || (yes
>= 3)) {
2115 /* violation, so mark all YES edges as errors */
2116 grid_dot
*d
= g
->dots
+ i
;
2118 for (j
= 0; j
< d
->order
; j
++) {
2119 int e
= d
->edges
[j
] - g
->edges
;
2120 if (state
->lines
[e
] == LINE_YES
)
2121 state
->line_errors
[e
] = TRUE
;
2128 /* ----------------------------------------------------------------------
2131 * Our solver modes operate as follows. Each mode also uses the modes above it.
2134 * Just implement the rules of the game.
2136 * Normal and Tricky Modes
2137 * For each (adjacent) pair of lines through each dot we store a bit for
2138 * whether at least one of them is on and whether at most one is on. (If we
2139 * know both or neither is on that's already stored more directly.)
2142 * Use edsf data structure to make equivalence classes of lines that are
2143 * known identical to or opposite to one another.
2148 * For general grids, we consider "dlines" to be pairs of lines joined
2149 * at a dot. The lines must be adjacent around the dot, so we can think of
2150 * a dline as being a dot+face combination. Or, a dot+edge combination where
2151 * the second edge is taken to be the next clockwise edge from the dot.
2152 * Original loopy code didn't have this extra restriction of the lines being
2153 * adjacent. From my tests with square grids, this extra restriction seems to
2154 * take little, if anything, away from the quality of the puzzles.
2155 * A dline can be uniquely identified by an edge/dot combination, given that
2156 * a dline-pair always goes clockwise around its common dot. The edge/dot
2157 * combination can be represented by an edge/bool combination - if bool is
2158 * TRUE, use edge->dot1 else use edge->dot2. So the total number of dlines is
2159 * exactly twice the number of edges in the grid - although the dlines
2160 * spanning the infinite face are not all that useful to the solver.
2161 * Note that, by convention, a dline goes clockwise around its common dot,
2162 * which means the dline goes anti-clockwise around its common face.
2165 /* Helper functions for obtaining an index into an array of dlines, given
2166 * various information. We assume the grid layout conventions about how
2167 * the various lists are interleaved - see grid_make_consistent() for
2170 /* i points to the first edge of the dline pair, reading clockwise around
2172 static int dline_index_from_dot(grid
*g
, grid_dot
*d
, int i
)
2174 grid_edge
*e
= d
->edges
[i
];
2179 if (i2
== d
->order
) i2
= 0;
2182 ret
= 2 * (e
- g
->edges
) + ((e
->dot1
== d
) ?
1 : 0);
2184 printf("dline_index_from_dot: d=%d,i=%d, edges [%d,%d] - %d\n",
2185 (int)(d
- g
->dots
), i
, (int)(e
- g
->edges
),
2186 (int)(e2
- g
->edges
), ret
);
2190 /* i points to the second edge of the dline pair, reading clockwise around
2191 * the face. That is, the edges of the dline, starting at edge{i}, read
2192 * anti-clockwise around the face. By layout conventions, the common dot
2193 * of the dline will be f->dots[i] */
2194 static int dline_index_from_face(grid
*g
, grid_face
*f
, int i
)
2196 grid_edge
*e
= f
->edges
[i
];
2197 grid_dot
*d
= f
->dots
[i
];
2202 if (i2
< 0) i2
+= f
->order
;
2205 ret
= 2 * (e
- g
->edges
) + ((e
->dot1
== d
) ?
1 : 0);
2207 printf("dline_index_from_face: f=%d,i=%d, edges [%d,%d] - %d\n",
2208 (int)(f
- g
->faces
), i
, (int)(e
- g
->edges
),
2209 (int)(e2
- g
->edges
), ret
);
2213 static int is_atleastone(const char *dline_array
, int index
)
2215 return BIT_SET(dline_array
[index
], 0);
2217 static int set_atleastone(char *dline_array
, int index
)
2219 return SET_BIT(dline_array
[index
], 0);
2221 static int is_atmostone(const char *dline_array
, int index
)
2223 return BIT_SET(dline_array
[index
], 1);
2225 static int set_atmostone(char *dline_array
, int index
)
2227 return SET_BIT(dline_array
[index
], 1);
2230 static void array_setall(char *array
, char from
, char to
, int len
)
2232 char *p
= array
, *p_old
= p
;
2233 int len_remaining
= len
;
2235 while ((p
= memchr(p
, from
, len_remaining
))) {
2237 len_remaining
-= p
- p_old
;
2242 /* Helper, called when doing dline dot deductions, in the case where we
2243 * have 4 UNKNOWNs, and two of them (adjacent) have *exactly* one YES between
2244 * them (because of dline atmostone/atleastone).
2245 * On entry, edge points to the first of these two UNKNOWNs. This function
2246 * will find the opposite UNKNOWNS (if they are adjacent to one another)
2247 * and set their corresponding dline to atleastone. (Setting atmostone
2248 * already happens in earlier dline deductions) */
2249 static int dline_set_opp_atleastone(solver_state
*sstate
,
2250 grid_dot
*d
, int edge
)
2252 game_state
*state
= sstate
->state
;
2253 grid
*g
= state
->game_grid
;
2256 for (opp
= 0; opp
< N
; opp
++) {
2257 int opp_dline_index
;
2258 if (opp
== edge
|| opp
== edge
+1 || opp
== edge
-1)
2260 if (opp
== 0 && edge
== N
-1)
2262 if (opp
== N
-1 && edge
== 0)
2265 if (opp2
== N
) opp2
= 0;
2266 /* Check if opp, opp2 point to LINE_UNKNOWNs */
2267 if (state
->lines
[d
->edges
[opp
] - g
->edges
] != LINE_UNKNOWN
)
2269 if (state
->lines
[d
->edges
[opp2
] - g
->edges
] != LINE_UNKNOWN
)
2271 /* Found opposite UNKNOWNS and they're next to each other */
2272 opp_dline_index
= dline_index_from_dot(g
, d
, opp
);
2273 return set_atleastone(sstate
->dlines
, opp_dline_index
);
2279 /* Set pairs of lines around this face which are known to be identical, to
2280 * the given line_state */
2281 static int face_setall_identical(solver_state
*sstate
, int face_index
,
2282 enum line_state line_new
)
2284 /* can[dir] contains the canonical line associated with the line in
2285 * direction dir from the square in question. Similarly inv[dir] is
2286 * whether or not the line in question is inverse to its canonical
2289 game_state
*state
= sstate
->state
;
2290 grid
*g
= state
->game_grid
;
2291 grid_face
*f
= g
->faces
+ face_index
;
2294 int can1
, can2
, inv1
, inv2
;
2296 for (i
= 0; i
< N
; i
++) {
2297 int line1_index
= f
->edges
[i
] - g
->edges
;
2298 if (state
->lines
[line1_index
] != LINE_UNKNOWN
)
2300 for (j
= i
+ 1; j
< N
; j
++) {
2301 int line2_index
= f
->edges
[j
] - g
->edges
;
2302 if (state
->lines
[line2_index
] != LINE_UNKNOWN
)
2305 /* Found two UNKNOWNS */
2306 can1
= edsf_canonify(sstate
->linedsf
, line1_index
, &inv1
);
2307 can2
= edsf_canonify(sstate
->linedsf
, line2_index
, &inv2
);
2308 if (can1
== can2
&& inv1
== inv2
) {
2309 solver_set_line(sstate
, line1_index
, line_new
);
2310 solver_set_line(sstate
, line2_index
, line_new
);
2317 /* Given a dot or face, and a count of LINE_UNKNOWNs, find them and
2318 * return the edge indices into e. */
2319 static void find_unknowns(game_state
*state
,
2320 grid_edge
**edge_list
, /* Edge list to search (from a face or a dot) */
2321 int expected_count
, /* Number of UNKNOWNs (comes from solver's cache) */
2322 int *e
/* Returned edge indices */)
2325 grid
*g
= state
->game_grid
;
2326 while (c
< expected_count
) {
2327 int line_index
= *edge_list
- g
->edges
;
2328 if (state
->lines
[line_index
] == LINE_UNKNOWN
) {
2336 /* If we have a list of edges, and we know whether the number of YESs should
2337 * be odd or even, and there are only a few UNKNOWNs, we can do some simple
2338 * linedsf deductions. This can be used for both face and dot deductions.
2339 * Returns the difficulty level of the next solver that should be used,
2340 * or DIFF_MAX if no progress was made. */
2341 static int parity_deductions(solver_state
*sstate
,
2342 grid_edge
**edge_list
, /* Edge list (from a face or a dot) */
2343 int total_parity
, /* Expected number of YESs modulo 2 (either 0 or 1) */
2346 game_state
*state
= sstate
->state
;
2347 int diff
= DIFF_MAX
;
2348 int *linedsf
= sstate
->linedsf
;
2350 if (unknown_count
== 2) {
2351 /* Lines are known alike/opposite, depending on inv. */
2353 find_unknowns(state
, edge_list
, 2, e
);
2354 if (merge_lines(sstate
, e
[0], e
[1], total_parity
))
2355 diff
= min(diff
, DIFF_HARD
);
2356 } else if (unknown_count
== 3) {
2358 int can
[3]; /* canonical edges */
2359 int inv
[3]; /* whether can[x] is inverse to e[x] */
2360 find_unknowns(state
, edge_list
, 3, e
);
2361 can
[0] = edsf_canonify(linedsf
, e
[0], inv
);
2362 can
[1] = edsf_canonify(linedsf
, e
[1], inv
+1);
2363 can
[2] = edsf_canonify(linedsf
, e
[2], inv
+2);
2364 if (can
[0] == can
[1]) {
2365 if (solver_set_line(sstate
, e
[2], (total_parity
^inv
[0]^inv
[1]) ?
2366 LINE_YES
: LINE_NO
))
2367 diff
= min(diff
, DIFF_EASY
);
2369 if (can
[0] == can
[2]) {
2370 if (solver_set_line(sstate
, e
[1], (total_parity
^inv
[0]^inv
[2]) ?
2371 LINE_YES
: LINE_NO
))
2372 diff
= min(diff
, DIFF_EASY
);
2374 if (can
[1] == can
[2]) {
2375 if (solver_set_line(sstate
, e
[0], (total_parity
^inv
[1]^inv
[2]) ?
2376 LINE_YES
: LINE_NO
))
2377 diff
= min(diff
, DIFF_EASY
);
2379 } else if (unknown_count
== 4) {
2381 int can
[4]; /* canonical edges */
2382 int inv
[4]; /* whether can[x] is inverse to e[x] */
2383 find_unknowns(state
, edge_list
, 4, e
);
2384 can
[0] = edsf_canonify(linedsf
, e
[0], inv
);
2385 can
[1] = edsf_canonify(linedsf
, e
[1], inv
+1);
2386 can
[2] = edsf_canonify(linedsf
, e
[2], inv
+2);
2387 can
[3] = edsf_canonify(linedsf
, e
[3], inv
+3);
2388 if (can
[0] == can
[1]) {
2389 if (merge_lines(sstate
, e
[2], e
[3], total_parity
^inv
[0]^inv
[1]))
2390 diff
= min(diff
, DIFF_HARD
);
2391 } else if (can
[0] == can
[2]) {
2392 if (merge_lines(sstate
, e
[1], e
[3], total_parity
^inv
[0]^inv
[2]))
2393 diff
= min(diff
, DIFF_HARD
);
2394 } else if (can
[0] == can
[3]) {
2395 if (merge_lines(sstate
, e
[1], e
[2], total_parity
^inv
[0]^inv
[3]))
2396 diff
= min(diff
, DIFF_HARD
);
2397 } else if (can
[1] == can
[2]) {
2398 if (merge_lines(sstate
, e
[0], e
[3], total_parity
^inv
[1]^inv
[2]))
2399 diff
= min(diff
, DIFF_HARD
);
2400 } else if (can
[1] == can
[3]) {
2401 if (merge_lines(sstate
, e
[0], e
[2], total_parity
^inv
[1]^inv
[3]))
2402 diff
= min(diff
, DIFF_HARD
);
2403 } else if (can
[2] == can
[3]) {
2404 if (merge_lines(sstate
, e
[0], e
[1], total_parity
^inv
[2]^inv
[3]))
2405 diff
= min(diff
, DIFF_HARD
);
2413 * These are the main solver functions.
2415 * Their return values are diff values corresponding to the lowest mode solver
2416 * that would notice the work that they have done. For example if the normal
2417 * mode solver adds actual lines or crosses, it will return DIFF_EASY as the
2418 * easy mode solver might be able to make progress using that. It doesn't make
2419 * sense for one of them to return a diff value higher than that of the
2422 * Each function returns the lowest value it can, as early as possible, in
2423 * order to try and pass as much work as possible back to the lower level
2424 * solvers which progress more quickly.
2427 /* PROPOSED NEW DESIGN:
2428 * We have a work queue consisting of 'events' notifying us that something has
2429 * happened that a particular solver mode might be interested in. For example
2430 * the hard mode solver might do something that helps the normal mode solver at
2431 * dot [x,y] in which case it will enqueue an event recording this fact. Then
2432 * we pull events off the work queue, and hand each in turn to the solver that
2433 * is interested in them. If a solver reports that it failed we pass the same
2434 * event on to progressively more advanced solvers and the loop detector. Once
2435 * we've exhausted an event, or it has helped us progress, we drop it and
2436 * continue to the next one. The events are sorted first in order of solver
2437 * complexity (easy first) then order of insertion (oldest first).
2438 * Once we run out of events we loop over each permitted solver in turn
2439 * (easiest first) until either a deduction is made (and an event therefore
2440 * emerges) or no further deductions can be made (in which case we've failed).
2443 * * How do we 'loop over' a solver when both dots and squares are concerned.
2444 * Answer: first all squares then all dots.
2447 static int trivial_deductions(solver_state
*sstate
)
2449 int i
, current_yes
, current_no
;
2450 game_state
*state
= sstate
->state
;
2451 grid
*g
= state
->game_grid
;
2452 int diff
= DIFF_MAX
;
2454 /* Per-face deductions */
2455 for (i
= 0; i
< g
->num_faces
; i
++) {
2456 grid_face
*f
= g
->faces
+ i
;
2458 if (sstate
->face_solved
[i
])
2461 current_yes
= sstate
->face_yes_count
[i
];
2462 current_no
= sstate
->face_no_count
[i
];
2464 if (current_yes
+ current_no
== f
->order
) {
2465 sstate
->face_solved
[i
] = TRUE
;
2469 if (state
->clues
[i
] < 0)
2473 * This code checks whether the numeric clue on a face is so
2474 * large as to permit all its remaining LINE_UNKNOWNs to be
2475 * filled in as LINE_YES, or alternatively so small as to
2476 * permit them all to be filled in as LINE_NO.
2479 if (state
->clues
[i
] < current_yes
) {
2480 sstate
->solver_status
= SOLVER_MISTAKE
;
2483 if (state
->clues
[i
] == current_yes
) {
2484 if (face_setall(sstate
, i
, LINE_UNKNOWN
, LINE_NO
))
2485 diff
= min(diff
, DIFF_EASY
);
2486 sstate
->face_solved
[i
] = TRUE
;
2490 if (f
->order
- state
->clues
[i
] < current_no
) {
2491 sstate
->solver_status
= SOLVER_MISTAKE
;
2494 if (f
->order
- state
->clues
[i
] == current_no
) {
2495 if (face_setall(sstate
, i
, LINE_UNKNOWN
, LINE_YES
))
2496 diff
= min(diff
, DIFF_EASY
);
2497 sstate
->face_solved
[i
] = TRUE
;
2501 if (f
->order
- state
->clues
[i
] == current_no
+ 1 &&
2502 f
->order
- current_yes
- current_no
> 2) {
2504 * One small refinement to the above: we also look for any
2505 * adjacent pair of LINE_UNKNOWNs around the face with
2506 * some LINE_YES incident on it from elsewhere. If we find
2507 * one, then we know that pair of LINE_UNKNOWNs can't
2508 * _both_ be LINE_YES, and hence that pushes us one line
2509 * closer to being able to determine all the rest.
2511 int j
, k
, e1
, e2
, e
, d
;
2513 for (j
= 0; j
< f
->order
; j
++) {
2514 e1
= f
->edges
[j
] - g
->edges
;
2515 e2
= f
->edges
[j
+1 < f
->order ? j
+1 : 0] - g
->edges
;
2517 if (g
->edges
[e1
].dot1
== g
->edges
[e2
].dot1
||
2518 g
->edges
[e1
].dot1
== g
->edges
[e2
].dot2
) {
2519 d
= g
->edges
[e1
].dot1
- g
->dots
;
2521 assert(g
->edges
[e1
].dot2
== g
->edges
[e2
].dot1
||
2522 g
->edges
[e1
].dot2
== g
->edges
[e2
].dot2
);
2523 d
= g
->edges
[e1
].dot2
- g
->dots
;
2526 if (state
->lines
[e1
] == LINE_UNKNOWN
&&
2527 state
->lines
[e2
] == LINE_UNKNOWN
) {
2528 for (k
= 0; k
< g
->dots
[d
].order
; k
++) {
2529 int e
= g
->dots
[d
].edges
[k
] - g
->edges
;
2530 if (state
->lines
[e
] == LINE_YES
)
2531 goto found
; /* multi-level break */
2539 * If we get here, we've found such a pair of edges, and
2540 * they're e1 and e2.
2542 for (j
= 0; j
< f
->order
; j
++) {
2543 e
= f
->edges
[j
] - g
->edges
;
2544 if (state
->lines
[e
] == LINE_UNKNOWN
&& e
!= e1
&& e
!= e2
) {
2545 int r
= solver_set_line(sstate
, e
, LINE_YES
);
2547 diff
= min(diff
, DIFF_EASY
);
2553 check_caches(sstate
);
2555 /* Per-dot deductions */
2556 for (i
= 0; i
< g
->num_dots
; i
++) {
2557 grid_dot
*d
= g
->dots
+ i
;
2558 int yes
, no
, unknown
;
2560 if (sstate
->dot_solved
[i
])
2563 yes
= sstate
->dot_yes_count
[i
];
2564 no
= sstate
->dot_no_count
[i
];
2565 unknown
= d
->order
- yes
- no
;
2569 sstate
->dot_solved
[i
] = TRUE
;
2570 } else if (unknown
== 1) {
2571 dot_setall(sstate
, i
, LINE_UNKNOWN
, LINE_NO
);
2572 diff
= min(diff
, DIFF_EASY
);
2573 sstate
->dot_solved
[i
] = TRUE
;
2575 } else if (yes
== 1) {
2577 sstate
->solver_status
= SOLVER_MISTAKE
;
2579 } else if (unknown
== 1) {
2580 dot_setall(sstate
, i
, LINE_UNKNOWN
, LINE_YES
);
2581 diff
= min(diff
, DIFF_EASY
);
2583 } else if (yes
== 2) {
2585 dot_setall(sstate
, i
, LINE_UNKNOWN
, LINE_NO
);
2586 diff
= min(diff
, DIFF_EASY
);
2588 sstate
->dot_solved
[i
] = TRUE
;
2590 sstate
->solver_status
= SOLVER_MISTAKE
;
2595 check_caches(sstate
);
2600 static int dline_deductions(solver_state
*sstate
)
2602 game_state
*state
= sstate
->state
;
2603 grid
*g
= state
->game_grid
;
2604 char *dlines
= sstate
->dlines
;
2606 int diff
= DIFF_MAX
;
2608 /* ------ Face deductions ------ */
2610 /* Given a set of dline atmostone/atleastone constraints, need to figure
2611 * out if we can deduce any further info. For more general faces than
2612 * squares, this turns out to be a tricky problem.
2613 * The approach taken here is to define (per face) NxN matrices:
2614 * "maxs" and "mins".
2615 * The entries maxs(j,k) and mins(j,k) define the upper and lower limits
2616 * for the possible number of edges that are YES between positions j and k
2617 * going clockwise around the face. Can think of j and k as marking dots
2618 * around the face (recall the labelling scheme: edge0 joins dot0 to dot1,
2619 * edge1 joins dot1 to dot2 etc).
2620 * Trivially, mins(j,j) = maxs(j,j) = 0, and we don't even bother storing
2621 * these. mins(j,j+1) and maxs(j,j+1) are determined by whether edge{j}
2622 * is YES, NO or UNKNOWN. mins(j,j+2) and maxs(j,j+2) are related to
2623 * the dline atmostone/atleastone status for edges j and j+1.
2625 * Then we calculate the remaining entries recursively. We definitely
2627 * mins(j,k) >= { mins(j,u) + mins(u,k) } for any u between j and k.
2628 * This is because any valid placement of YESs between j and k must give
2629 * a valid placement between j and u, and also between u and k.
2630 * I believe it's sufficient to use just the two values of u:
2631 * j+1 and j+2. Seems to work well in practice - the bounds we compute
2632 * are rigorous, even if they might not be best-possible.
2634 * Once we have maxs and mins calculated, we can make inferences about
2635 * each dline{j,j+1} by looking at the possible complementary edge-counts
2636 * mins(j+2,j) and maxs(j+2,j) and comparing these with the face clue.
2637 * As well as dlines, we can make similar inferences about single edges.
2638 * For example, consider a pentagon with clue 3, and we know at most one
2639 * of (edge0, edge1) is YES, and at most one of (edge2, edge3) is YES.
2640 * We could then deduce edge4 is YES, because maxs(0,4) would be 2, so
2641 * that final edge would have to be YES to make the count up to 3.
2644 /* Much quicker to allocate arrays on the stack than the heap, so
2645 * define the largest possible face size, and base our array allocations
2646 * on that. We check this with an assertion, in case someone decides to
2647 * make a grid which has larger faces than this. Note, this algorithm
2648 * could get quite expensive if there are many large faces. */
2649 #define MAX_FACE_SIZE 12
2651 for (i
= 0; i
< g
->num_faces
; i
++) {
2652 int maxs
[MAX_FACE_SIZE
][MAX_FACE_SIZE
];
2653 int mins
[MAX_FACE_SIZE
][MAX_FACE_SIZE
];
2654 grid_face
*f
= g
->faces
+ i
;
2657 int clue
= state
->clues
[i
];
2658 assert(N
<= MAX_FACE_SIZE
);
2659 if (sstate
->face_solved
[i
])
2661 if (clue
< 0) continue;
2663 /* Calculate the (j,j+1) entries */
2664 for (j
= 0; j
< N
; j
++) {
2665 int edge_index
= f
->edges
[j
] - g
->edges
;
2667 enum line_state line1
= state
->lines
[edge_index
];
2668 enum line_state line2
;
2672 maxs
[j
][k
] = (line1
== LINE_NO
) ?
0 : 1;
2673 mins
[j
][k
] = (line1
== LINE_YES
) ?
1 : 0;
2674 /* Calculate the (j,j+2) entries */
2675 dline_index
= dline_index_from_face(g
, f
, k
);
2676 edge_index
= f
->edges
[k
] - g
->edges
;
2677 line2
= state
->lines
[edge_index
];
2683 if (line1
== LINE_NO
) tmp
--;
2684 if (line2
== LINE_NO
) tmp
--;
2685 if (tmp
== 2 && is_atmostone(dlines
, dline_index
))
2691 if (line1
== LINE_YES
) tmp
++;
2692 if (line2
== LINE_YES
) tmp
++;
2693 if (tmp
== 0 && is_atleastone(dlines
, dline_index
))
2698 /* Calculate the (j,j+m) entries for m between 3 and N-1 */
2699 for (m
= 3; m
< N
; m
++) {
2700 for (j
= 0; j
< N
; j
++) {
2708 maxs
[j
][k
] = maxs
[j
][u
] + maxs
[u
][k
];
2709 mins
[j
][k
] = mins
[j
][u
] + mins
[u
][k
];
2710 tmp
= maxs
[j
][v
] + maxs
[v
][k
];
2711 maxs
[j
][k
] = min(maxs
[j
][k
], tmp
);
2712 tmp
= mins
[j
][v
] + mins
[v
][k
];
2713 mins
[j
][k
] = max(mins
[j
][k
], tmp
);
2717 /* See if we can make any deductions */
2718 for (j
= 0; j
< N
; j
++) {
2720 grid_edge
*e
= f
->edges
[j
];
2721 int line_index
= e
- g
->edges
;
2724 if (state
->lines
[line_index
] != LINE_UNKNOWN
)
2729 /* minimum YESs in the complement of this edge */
2730 if (mins
[k
][j
] > clue
) {
2731 sstate
->solver_status
= SOLVER_MISTAKE
;
2734 if (mins
[k
][j
] == clue
) {
2735 /* setting this edge to YES would make at least
2736 * (clue+1) edges - contradiction */
2737 solver_set_line(sstate
, line_index
, LINE_NO
);
2738 diff
= min(diff
, DIFF_EASY
);
2740 if (maxs
[k
][j
] < clue
- 1) {
2741 sstate
->solver_status
= SOLVER_MISTAKE
;
2744 if (maxs
[k
][j
] == clue
- 1) {
2745 /* Only way to satisfy the clue is to set edge{j} as YES */
2746 solver_set_line(sstate
, line_index
, LINE_YES
);
2747 diff
= min(diff
, DIFF_EASY
);
2750 /* More advanced deduction that allows propagation along diagonal
2751 * chains of faces connected by dots, for example, 3-2-...-2-3
2752 * in square grids. */
2753 if (sstate
->diff
>= DIFF_TRICKY
) {
2754 /* Now see if we can make dline deduction for edges{j,j+1} */
2756 if (state
->lines
[e
- g
->edges
] != LINE_UNKNOWN
)
2757 /* Only worth doing this for an UNKNOWN,UNKNOWN pair.
2758 * Dlines where one of the edges is known, are handled in the
2762 dline_index
= dline_index_from_face(g
, f
, k
);
2766 /* minimum YESs in the complement of this dline */
2767 if (mins
[k
][j
] > clue
- 2) {
2768 /* Adding 2 YESs would break the clue */
2769 if (set_atmostone(dlines
, dline_index
))
2770 diff
= min(diff
, DIFF_NORMAL
);
2772 /* maximum YESs in the complement of this dline */
2773 if (maxs
[k
][j
] < clue
) {
2774 /* Adding 2 NOs would mean not enough YESs */
2775 if (set_atleastone(dlines
, dline_index
))
2776 diff
= min(diff
, DIFF_NORMAL
);
2782 if (diff
< DIFF_NORMAL
)
2785 /* ------ Dot deductions ------ */
2787 for (i
= 0; i
< g
->num_dots
; i
++) {
2788 grid_dot
*d
= g
->dots
+ i
;
2790 int yes
, no
, unknown
;
2792 if (sstate
->dot_solved
[i
])
2794 yes
= sstate
->dot_yes_count
[i
];
2795 no
= sstate
->dot_no_count
[i
];
2796 unknown
= N
- yes
- no
;
2798 for (j
= 0; j
< N
; j
++) {
2801 int line1_index
, line2_index
;
2802 enum line_state line1
, line2
;
2805 dline_index
= dline_index_from_dot(g
, d
, j
);
2806 line1_index
= d
->edges
[j
] - g
->edges
;
2807 line2_index
= d
->edges
[k
] - g
->edges
;
2808 line1
= state
->lines
[line1_index
];
2809 line2
= state
->lines
[line2_index
];
2811 /* Infer dline state from line state */
2812 if (line1
== LINE_NO
|| line2
== LINE_NO
) {
2813 if (set_atmostone(dlines
, dline_index
))
2814 diff
= min(diff
, DIFF_NORMAL
);
2816 if (line1
== LINE_YES
|| line2
== LINE_YES
) {
2817 if (set_atleastone(dlines
, dline_index
))
2818 diff
= min(diff
, DIFF_NORMAL
);
2820 /* Infer line state from dline state */
2821 if (is_atmostone(dlines
, dline_index
)) {
2822 if (line1
== LINE_YES
&& line2
== LINE_UNKNOWN
) {
2823 solver_set_line(sstate
, line2_index
, LINE_NO
);
2824 diff
= min(diff
, DIFF_EASY
);
2826 if (line2
== LINE_YES
&& line1
== LINE_UNKNOWN
) {
2827 solver_set_line(sstate
, line1_index
, LINE_NO
);
2828 diff
= min(diff
, DIFF_EASY
);
2831 if (is_atleastone(dlines
, dline_index
)) {
2832 if (line1
== LINE_NO
&& line2
== LINE_UNKNOWN
) {
2833 solver_set_line(sstate
, line2_index
, LINE_YES
);
2834 diff
= min(diff
, DIFF_EASY
);
2836 if (line2
== LINE_NO
&& line1
== LINE_UNKNOWN
) {
2837 solver_set_line(sstate
, line1_index
, LINE_YES
);
2838 diff
= min(diff
, DIFF_EASY
);
2841 /* Deductions that depend on the numbers of lines.
2842 * Only bother if both lines are UNKNOWN, otherwise the
2843 * easy-mode solver (or deductions above) would have taken
2845 if (line1
!= LINE_UNKNOWN
|| line2
!= LINE_UNKNOWN
)
2848 if (yes
== 0 && unknown
== 2) {
2849 /* Both these unknowns must be identical. If we know
2850 * atmostone or atleastone, we can make progress. */
2851 if (is_atmostone(dlines
, dline_index
)) {
2852 solver_set_line(sstate
, line1_index
, LINE_NO
);
2853 solver_set_line(sstate
, line2_index
, LINE_NO
);
2854 diff
= min(diff
, DIFF_EASY
);
2856 if (is_atleastone(dlines
, dline_index
)) {
2857 solver_set_line(sstate
, line1_index
, LINE_YES
);
2858 solver_set_line(sstate
, line2_index
, LINE_YES
);
2859 diff
= min(diff
, DIFF_EASY
);
2863 if (set_atmostone(dlines
, dline_index
))
2864 diff
= min(diff
, DIFF_NORMAL
);
2866 if (set_atleastone(dlines
, dline_index
))
2867 diff
= min(diff
, DIFF_NORMAL
);
2871 /* More advanced deduction that allows propagation along diagonal
2872 * chains of faces connected by dots, for example: 3-2-...-2-3
2873 * in square grids. */
2874 if (sstate
->diff
>= DIFF_TRICKY
) {
2875 /* If we have atleastone set for this dline, infer
2876 * atmostone for each "opposite" dline (that is, each
2877 * dline without edges in common with this one).
2878 * Again, this test is only worth doing if both these
2879 * lines are UNKNOWN. For if one of these lines were YES,
2880 * the (yes == 1) test above would kick in instead. */
2881 if (is_atleastone(dlines
, dline_index
)) {
2883 for (opp
= 0; opp
< N
; opp
++) {
2884 int opp_dline_index
;
2885 if (opp
== j
|| opp
== j
+1 || opp
== j
-1)
2887 if (j
== 0 && opp
== N
-1)
2889 if (j
== N
-1 && opp
== 0)
2891 opp_dline_index
= dline_index_from_dot(g
, d
, opp
);
2892 if (set_atmostone(dlines
, opp_dline_index
))
2893 diff
= min(diff
, DIFF_NORMAL
);
2895 if (yes
== 0 && is_atmostone(dlines
, dline_index
)) {
2896 /* This dline has *exactly* one YES and there are no
2897 * other YESs. This allows more deductions. */
2899 /* Third unknown must be YES */
2900 for (opp
= 0; opp
< N
; opp
++) {
2902 if (opp
== j
|| opp
== k
)
2904 opp_index
= d
->edges
[opp
] - g
->edges
;
2905 if (state
->lines
[opp_index
] == LINE_UNKNOWN
) {
2906 solver_set_line(sstate
, opp_index
,
2908 diff
= min(diff
, DIFF_EASY
);
2911 } else if (unknown
== 4) {
2912 /* Exactly one of opposite UNKNOWNS is YES. We've
2913 * already set atmostone, so set atleastone as
2916 if (dline_set_opp_atleastone(sstate
, d
, j
))
2917 diff
= min(diff
, DIFF_NORMAL
);
2927 static int linedsf_deductions(solver_state
*sstate
)
2929 game_state
*state
= sstate
->state
;
2930 grid
*g
= state
->game_grid
;
2931 char *dlines
= sstate
->dlines
;
2933 int diff
= DIFF_MAX
;
2936 /* ------ Face deductions ------ */
2938 /* A fully-general linedsf deduction seems overly complicated
2939 * (I suspect the problem is NP-complete, though in practice it might just
2940 * be doable because faces are limited in size).
2941 * For simplicity, we only consider *pairs* of LINE_UNKNOWNS that are
2942 * known to be identical. If setting them both to YES (or NO) would break
2943 * the clue, set them to NO (or YES). */
2945 for (i
= 0; i
< g
->num_faces
; i
++) {
2946 int N
, yes
, no
, unknown
;
2949 if (sstate
->face_solved
[i
])
2951 clue
= state
->clues
[i
];
2955 N
= g
->faces
[i
].order
;
2956 yes
= sstate
->face_yes_count
[i
];
2957 if (yes
+ 1 == clue
) {
2958 if (face_setall_identical(sstate
, i
, LINE_NO
))
2959 diff
= min(diff
, DIFF_EASY
);
2961 no
= sstate
->face_no_count
[i
];
2962 if (no
+ 1 == N
- clue
) {
2963 if (face_setall_identical(sstate
, i
, LINE_YES
))
2964 diff
= min(diff
, DIFF_EASY
);
2967 /* Reload YES count, it might have changed */
2968 yes
= sstate
->face_yes_count
[i
];
2969 unknown
= N
- no
- yes
;
2971 /* Deductions with small number of LINE_UNKNOWNs, based on overall
2972 * parity of lines. */
2973 diff_tmp
= parity_deductions(sstate
, g
->faces
[i
].edges
,
2974 (clue
- yes
) % 2, unknown
);
2975 diff
= min(diff
, diff_tmp
);
2978 /* ------ Dot deductions ------ */
2979 for (i
= 0; i
< g
->num_dots
; i
++) {
2980 grid_dot
*d
= g
->dots
+ i
;
2983 int yes
, no
, unknown
;
2984 /* Go through dlines, and do any dline<->linedsf deductions wherever
2985 * we find two UNKNOWNS. */
2986 for (j
= 0; j
< N
; j
++) {
2987 int dline_index
= dline_index_from_dot(g
, d
, j
);
2990 int can1
, can2
, inv1
, inv2
;
2992 line1_index
= d
->edges
[j
] - g
->edges
;
2993 if (state
->lines
[line1_index
] != LINE_UNKNOWN
)
2996 if (j2
== N
) j2
= 0;
2997 line2_index
= d
->edges
[j2
] - g
->edges
;
2998 if (state
->lines
[line2_index
] != LINE_UNKNOWN
)
3000 /* Infer dline flags from linedsf */
3001 can1
= edsf_canonify(sstate
->linedsf
, line1_index
, &inv1
);
3002 can2
= edsf_canonify(sstate
->linedsf
, line2_index
, &inv2
);
3003 if (can1
== can2
&& inv1
!= inv2
) {
3004 /* These are opposites, so set dline atmostone/atleastone */
3005 if (set_atmostone(dlines
, dline_index
))
3006 diff
= min(diff
, DIFF_NORMAL
);
3007 if (set_atleastone(dlines
, dline_index
))
3008 diff
= min(diff
, DIFF_NORMAL
);
3011 /* Infer linedsf from dline flags */
3012 if (is_atmostone(dlines
, dline_index
)
3013 && is_atleastone(dlines
, dline_index
)) {
3014 if (merge_lines(sstate
, line1_index
, line2_index
, 1))
3015 diff
= min(diff
, DIFF_HARD
);
3019 /* Deductions with small number of LINE_UNKNOWNs, based on overall
3020 * parity of lines. */
3021 yes
= sstate
->dot_yes_count
[i
];
3022 no
= sstate
->dot_no_count
[i
];
3023 unknown
= N
- yes
- no
;
3024 diff_tmp
= parity_deductions(sstate
, d
->edges
,
3026 diff
= min(diff
, diff_tmp
);
3029 /* ------ Edge dsf deductions ------ */
3031 /* If the state of a line is known, deduce the state of its canonical line
3032 * too, and vice versa. */
3033 for (i
= 0; i
< g
->num_edges
; i
++) {
3036 can
= edsf_canonify(sstate
->linedsf
, i
, &inv
);
3039 s
= sstate
->state
->lines
[can
];
3040 if (s
!= LINE_UNKNOWN
) {
3041 if (solver_set_line(sstate
, i
, inv ?
OPP(s
) : s
))
3042 diff
= min(diff
, DIFF_EASY
);
3044 s
= sstate
->state
->lines
[i
];
3045 if (s
!= LINE_UNKNOWN
) {
3046 if (solver_set_line(sstate
, can
, inv ?
OPP(s
) : s
))
3047 diff
= min(diff
, DIFF_EASY
);
3055 static int loop_deductions(solver_state
*sstate
)
3057 int edgecount
= 0, clues
= 0, satclues
= 0, sm1clues
= 0;
3058 game_state
*state
= sstate
->state
;
3059 grid
*g
= state
->game_grid
;
3060 int shortest_chainlen
= g
->num_dots
;
3061 int loop_found
= FALSE
;
3063 int progress
= FALSE
;
3067 * Go through the grid and update for all the new edges.
3068 * Since merge_dots() is idempotent, the simplest way to
3069 * do this is just to update for _all_ the edges.
3070 * Also, while we're here, we count the edges.
3072 for (i
= 0; i
< g
->num_edges
; i
++) {
3073 if (state
->lines
[i
] == LINE_YES
) {
3074 loop_found
|= merge_dots(sstate
, i
);
3080 * Count the clues, count the satisfied clues, and count the
3081 * satisfied-minus-one clues.
3083 for (i
= 0; i
< g
->num_faces
; i
++) {
3084 int c
= state
->clues
[i
];
3086 int o
= sstate
->face_yes_count
[i
];
3095 for (i
= 0; i
< g
->num_dots
; ++i
) {
3097 sstate
->looplen
[dsf_canonify(sstate
->dotdsf
, i
)];
3098 if (dots_connected
> 1)
3099 shortest_chainlen
= min(shortest_chainlen
, dots_connected
);
3102 assert(sstate
->solver_status
== SOLVER_INCOMPLETE
);
3104 if (satclues
== clues
&& shortest_chainlen
== edgecount
) {
3105 sstate
->solver_status
= SOLVER_SOLVED
;
3106 /* This discovery clearly counts as progress, even if we haven't
3107 * just added any lines or anything */
3109 goto finished_loop_deductionsing
;
3113 * Now go through looking for LINE_UNKNOWN edges which
3114 * connect two dots that are already in the same
3115 * equivalence class. If we find one, test to see if the
3116 * loop it would create is a solution.
3118 for (i
= 0; i
< g
->num_edges
; i
++) {
3119 grid_edge
*e
= g
->edges
+ i
;
3120 int d1
= e
->dot1
- g
->dots
;
3121 int d2
= e
->dot2
- g
->dots
;
3123 if (state
->lines
[i
] != LINE_UNKNOWN
)
3126 eqclass
= dsf_canonify(sstate
->dotdsf
, d1
);
3127 if (eqclass
!= dsf_canonify(sstate
->dotdsf
, d2
))
3130 val
= LINE_NO
; /* loop is bad until proven otherwise */
3133 * This edge would form a loop. Next
3134 * question: how long would the loop be?
3135 * Would it equal the total number of edges
3136 * (plus the one we'd be adding if we added
3139 if (sstate
->looplen
[eqclass
] == edgecount
+ 1) {
3143 * This edge would form a loop which
3144 * took in all the edges in the entire
3145 * grid. So now we need to work out
3146 * whether it would be a valid solution
3147 * to the puzzle, which means we have to
3148 * check if it satisfies all the clues.
3149 * This means that every clue must be
3150 * either satisfied or satisfied-minus-
3151 * 1, and also that the number of
3152 * satisfied-minus-1 clues must be at
3153 * most two and they must lie on either
3154 * side of this edge.
3158 int f
= e
->face1
- g
->faces
;
3159 int c
= state
->clues
[f
];
3160 if (c
>= 0 && sstate
->face_yes_count
[f
] == c
- 1)
3164 int f
= e
->face2
- g
->faces
;
3165 int c
= state
->clues
[f
];
3166 if (c
>= 0 && sstate
->face_yes_count
[f
] == c
- 1)
3169 if (sm1clues
== sm1_nearby
&&
3170 sm1clues
+ satclues
== clues
) {
3171 val
= LINE_YES
; /* loop is good! */
3176 * Right. Now we know that adding this edge
3177 * would form a loop, and we know whether
3178 * that loop would be a viable solution or
3181 * If adding this edge produces a solution,
3182 * then we know we've found _a_ solution but
3183 * we don't know that it's _the_ solution -
3184 * if it were provably the solution then
3185 * we'd have deduced this edge some time ago
3186 * without the need to do loop detection. So
3187 * in this state we return SOLVER_AMBIGUOUS,
3188 * which has the effect that hitting Solve
3189 * on a user-provided puzzle will fill in a
3190 * solution but using the solver to
3191 * construct new puzzles won't consider this
3192 * a reasonable deduction for the user to
3195 progress
= solver_set_line(sstate
, i
, val
);
3196 assert(progress
== TRUE
);
3197 if (val
== LINE_YES
) {
3198 sstate
->solver_status
= SOLVER_AMBIGUOUS
;
3199 goto finished_loop_deductionsing
;
3203 finished_loop_deductionsing
:
3204 return progress ? DIFF_EASY
: DIFF_MAX
;
3207 /* This will return a dynamically allocated solver_state containing the (more)
3209 static solver_state
*solve_game_rec(const solver_state
*sstate_start
)
3211 solver_state
*sstate
;
3213 /* Index of the solver we should call next. */
3216 /* As a speed-optimisation, we avoid re-running solvers that we know
3217 * won't make any progress. This happens when a high-difficulty
3218 * solver makes a deduction that can only help other high-difficulty
3220 * For example: if a new 'dline' flag is set by dline_deductions, the
3221 * trivial_deductions solver cannot do anything with this information.
3222 * If we've already run the trivial_deductions solver (because it's
3223 * earlier in the list), there's no point running it again.
3225 * Therefore: if a solver is earlier in the list than "threshold_index",
3226 * we don't bother running it if it's difficulty level is less than
3229 int threshold_diff
= 0;
3230 int threshold_index
= 0;
3232 sstate
= dup_solver_state(sstate_start
);
3234 check_caches(sstate
);
3236 while (i
< NUM_SOLVERS
) {
3237 if (sstate
->solver_status
== SOLVER_MISTAKE
)
3239 if (sstate
->solver_status
== SOLVER_SOLVED
||
3240 sstate
->solver_status
== SOLVER_AMBIGUOUS
) {
3241 /* solver finished */
3245 if ((solver_diffs
[i
] >= threshold_diff
|| i
>= threshold_index
)
3246 && solver_diffs
[i
] <= sstate
->diff
) {
3247 /* current_solver is eligible, so use it */
3248 int next_diff
= solver_fns
[i
](sstate
);
3249 if (next_diff
!= DIFF_MAX
) {
3250 /* solver made progress, so use new thresholds and
3251 * start again at top of list. */
3252 threshold_diff
= next_diff
;
3253 threshold_index
= i
;
3258 /* current_solver is ineligible, or failed to make progress, so
3259 * go to the next solver in the list */
3263 if (sstate
->solver_status
== SOLVER_SOLVED
||
3264 sstate
->solver_status
== SOLVER_AMBIGUOUS
) {
3265 /* s/LINE_UNKNOWN/LINE_NO/g */
3266 array_setall(sstate
->state
->lines
, LINE_UNKNOWN
, LINE_NO
,
3267 sstate
->state
->game_grid
->num_edges
);
3274 static char *solve_game(game_state
*state
, game_state
*currstate
,
3275 char *aux
, char **error
)
3278 solver_state
*sstate
, *new_sstate
;
3280 sstate
= new_solver_state(state
, DIFF_MAX
);
3281 new_sstate
= solve_game_rec(sstate
);
3283 if (new_sstate
->solver_status
== SOLVER_SOLVED
) {
3284 soln
= encode_solve_move(new_sstate
->state
);
3285 } else if (new_sstate
->solver_status
== SOLVER_AMBIGUOUS
) {
3286 soln
= encode_solve_move(new_sstate
->state
);
3287 /**error = "Solver found ambiguous solutions"; */
3289 soln
= encode_solve_move(new_sstate
->state
);
3290 /**error = "Solver failed"; */
3293 free_solver_state(new_sstate
);
3294 free_solver_state(sstate
);
3299 /* ----------------------------------------------------------------------
3300 * Drawing and mouse-handling
3303 static char *interpret_move(game_state
*state
, game_ui
*ui
, game_drawstate
*ds
,
3304 int x
, int y
, int button
)
3306 grid
*g
= state
->game_grid
;
3310 char button_char
= ' ';
3311 enum line_state old_state
;
3313 button
&= ~MOD_MASK
;
3315 /* Convert mouse-click (x,y) to grid coordinates */
3316 x
-= BORDER(ds
->tilesize
);
3317 y
-= BORDER(ds
->tilesize
);
3318 x
= x
* g
->tilesize
/ ds
->tilesize
;
3319 y
= y
* g
->tilesize
/ ds
->tilesize
;
3323 e
= grid_nearest_edge(g
, x
, y
);
3329 /* I think it's only possible to play this game with mouse clicks, sorry */
3330 /* Maybe will add mouse drag support some time */
3331 old_state
= state
->lines
[i
];
3335 switch (old_state
) {
3353 switch (old_state
) {
3372 sprintf(buf
, "%d%c", i
, (int)button_char
);
3378 static game_state
*execute_move(game_state
*state
, char *move
)
3381 game_state
*newstate
= dup_game(state
);
3383 if (move
[0] == 'S') {
3385 newstate
->cheated
= TRUE
;
3390 if (i
< 0 || i
>= newstate
->game_grid
->num_edges
)
3392 move
+= strspn(move
, "1234567890");
3393 switch (*(move
++)) {
3395 newstate
->lines
[i
] = LINE_YES
;
3398 newstate
->lines
[i
] = LINE_NO
;
3401 newstate
->lines
[i
] = LINE_UNKNOWN
;
3409 * Check for completion.
3411 if (check_completion(newstate
))
3412 newstate
->solved
= TRUE
;
3417 free_game(newstate
);
3421 /* ----------------------------------------------------------------------
3425 /* Convert from grid coordinates to screen coordinates */
3426 static void grid_to_screen(const game_drawstate
*ds
, const grid
*g
,
3427 int grid_x
, int grid_y
, int *x
, int *y
)
3429 *x
= grid_x
- g
->lowest_x
;
3430 *y
= grid_y
- g
->lowest_y
;
3431 *x
= *x
* ds
->tilesize
/ g
->tilesize
;
3432 *y
= *y
* ds
->tilesize
/ g
->tilesize
;
3433 *x
+= BORDER(ds
->tilesize
);
3434 *y
+= BORDER(ds
->tilesize
);
3437 /* Returns (into x,y) position of centre of face for rendering the text clue.
3439 static void face_text_pos(const game_drawstate
*ds
, const grid
*g
,
3440 grid_face
*f
, int *xret
, int *yret
)
3442 int faceindex
= f
- g
->faces
;
3445 * Return the cached position for this face, if we've already
3448 if (ds
->textx
[faceindex
] >= 0) {
3449 *xret
= ds
->textx
[faceindex
];
3450 *yret
= ds
->texty
[faceindex
];
3455 * Otherwise, use the incentre computed by grid.c and convert it
3456 * to screen coordinates.
3458 grid_find_incentre(f
);
3459 grid_to_screen(ds
, g
, f
->ix
, f
->iy
,
3460 &ds
->textx
[faceindex
], &ds
->texty
[faceindex
]);
3462 *xret
= ds
->textx
[faceindex
];
3463 *yret
= ds
->texty
[faceindex
];
3466 static void face_text_bbox(game_drawstate
*ds
, grid
*g
, grid_face
*f
,
3467 int *x
, int *y
, int *w
, int *h
)
3470 face_text_pos(ds
, g
, f
, &xx
, &yy
);
3472 /* There seems to be a certain amount of trial-and-error involved
3473 * in working out the correct bounding-box for the text. */
3475 *x
= xx
- ds
->tilesize
/4 - 1;
3476 *y
= yy
- ds
->tilesize
/4 - 3;
3477 *w
= ds
->tilesize
/2 + 2;
3478 *h
= ds
->tilesize
/2 + 5;
3481 static void game_redraw_clue(drawing
*dr
, game_drawstate
*ds
,
3482 game_state
*state
, int i
)
3484 grid
*g
= state
->game_grid
;
3485 grid_face
*f
= g
->faces
+ i
;
3489 if (state
->clues
[i
] < 10) {
3490 c
[0] = CLUE2CHAR(state
->clues
[i
]);
3493 sprintf(c
, "%d", state
->clues
[i
]);
3496 face_text_pos(ds
, g
, f
, &x
, &y
);
3498 FONT_VARIABLE
, ds
->tilesize
/2,
3499 ALIGN_VCENTRE
| ALIGN_HCENTRE
,
3500 ds
->clue_error
[i
] ? COL_MISTAKE
:
3501 ds
->clue_satisfied
[i
] ? COL_SATISFIED
: COL_FOREGROUND
, c
);
3504 static void edge_bbox(game_drawstate
*ds
, grid
*g
, grid_edge
*e
,
3505 int *x
, int *y
, int *w
, int *h
)
3507 int x1
= e
->dot1
->x
;
3508 int y1
= e
->dot1
->y
;
3509 int x2
= e
->dot2
->x
;
3510 int y2
= e
->dot2
->y
;
3511 int xmin
, xmax
, ymin
, ymax
;
3513 grid_to_screen(ds
, g
, x1
, y1
, &x1
, &y1
);
3514 grid_to_screen(ds
, g
, x2
, y2
, &x2
, &y2
);
3515 /* Allow extra margin for dots, and thickness of lines */
3516 xmin
= min(x1
, x2
) - 2;
3517 xmax
= max(x1
, x2
) + 2;
3518 ymin
= min(y1
, y2
) - 2;
3519 ymax
= max(y1
, y2
) + 2;
3523 *w
= xmax
- xmin
+ 1;
3524 *h
= ymax
- ymin
+ 1;
3527 static void dot_bbox(game_drawstate
*ds
, grid
*g
, grid_dot
*d
,
3528 int *x
, int *y
, int *w
, int *h
)
3532 grid_to_screen(ds
, g
, d
->x
, d
->y
, &x1
, &y1
);
3540 static const int loopy_line_redraw_phases
[] = {
3541 COL_FAINT
, COL_LINEUNKNOWN
, COL_FOREGROUND
, COL_HIGHLIGHT
, COL_MISTAKE
3543 #define NPHASES lenof(loopy_line_redraw_phases)
3545 static void game_redraw_line(drawing
*dr
, game_drawstate
*ds
,
3546 game_state
*state
, int i
, int phase
)
3548 grid
*g
= state
->game_grid
;
3549 grid_edge
*e
= g
->edges
+ i
;
3553 if (state
->line_errors
[i
])
3554 line_colour
= COL_MISTAKE
;
3555 else if (state
->lines
[i
] == LINE_UNKNOWN
)
3556 line_colour
= COL_LINEUNKNOWN
;
3557 else if (state
->lines
[i
] == LINE_NO
)
3558 line_colour
= COL_FAINT
;
3559 else if (ds
->flashing
)
3560 line_colour
= COL_HIGHLIGHT
;
3562 line_colour
= COL_FOREGROUND
;
3563 if (line_colour
!= loopy_line_redraw_phases
[phase
])
3566 /* Convert from grid to screen coordinates */
3567 grid_to_screen(ds
, g
, e
->dot1
->x
, e
->dot1
->y
, &x1
, &y1
);
3568 grid_to_screen(ds
, g
, e
->dot2
->x
, e
->dot2
->y
, &x2
, &y2
);
3570 if (line_colour
== COL_FAINT
) {
3571 static int draw_faint_lines
= -1;
3572 if (draw_faint_lines
< 0) {
3573 char *env
= getenv("LOOPY_FAINT_LINES");
3574 draw_faint_lines
= (!env
|| (env
[0] == 'y' ||
3577 if (draw_faint_lines
)
3578 draw_line(dr
, x1
, y1
, x2
, y2
, line_colour
);
3580 draw_thick_line(dr
, 3.0,
3587 static void game_redraw_dot(drawing
*dr
, game_drawstate
*ds
,
3588 game_state
*state
, int i
)
3590 grid
*g
= state
->game_grid
;
3591 grid_dot
*d
= g
->dots
+ i
;
3594 grid_to_screen(ds
, g
, d
->x
, d
->y
, &x
, &y
);
3595 draw_circle(dr
, x
, y
, 2, COL_FOREGROUND
, COL_FOREGROUND
);
3598 static int boxes_intersect(int x0
, int y0
, int w0
, int h0
,
3599 int x1
, int y1
, int w1
, int h1
)
3602 * Two intervals intersect iff neither is wholly on one side of
3603 * the other. Two boxes intersect iff their horizontal and
3604 * vertical intervals both intersect.
3606 return (x0
< x1
+w1
&& x1
< x0
+w0
&& y0
< y1
+h1
&& y1
< y0
+h0
);
3609 static void game_redraw_in_rect(drawing
*dr
, game_drawstate
*ds
,
3610 game_state
*state
, int x
, int y
, int w
, int h
)
3612 grid
*g
= state
->game_grid
;
3616 clip(dr
, x
, y
, w
, h
);
3617 draw_rect(dr
, x
, y
, w
, h
, COL_BACKGROUND
);
3619 for (i
= 0; i
< g
->num_faces
; i
++) {
3620 if (state
->clues
[i
] >= 0) {
3621 face_text_bbox(ds
, g
, &g
->faces
[i
], &bx
, &by
, &bw
, &bh
);
3622 if (boxes_intersect(x
, y
, w
, h
, bx
, by
, bw
, bh
))
3623 game_redraw_clue(dr
, ds
, state
, i
);
3626 for (phase
= 0; phase
< NPHASES
; phase
++) {
3627 for (i
= 0; i
< g
->num_edges
; i
++) {
3628 edge_bbox(ds
, g
, &g
->edges
[i
], &bx
, &by
, &bw
, &bh
);
3629 if (boxes_intersect(x
, y
, w
, h
, bx
, by
, bw
, bh
))
3630 game_redraw_line(dr
, ds
, state
, i
, phase
);
3633 for (i
= 0; i
< g
->num_dots
; i
++) {
3634 dot_bbox(ds
, g
, &g
->dots
[i
], &bx
, &by
, &bw
, &bh
);
3635 if (boxes_intersect(x
, y
, w
, h
, bx
, by
, bw
, bh
))
3636 game_redraw_dot(dr
, ds
, state
, i
);
3640 draw_update(dr
, x
, y
, w
, h
);
3643 static void game_redraw(drawing
*dr
, game_drawstate
*ds
, game_state
*oldstate
,
3644 game_state
*state
, int dir
, game_ui
*ui
,
3645 float animtime
, float flashtime
)
3647 #define REDRAW_OBJECTS_LIMIT 16 /* Somewhat arbitrary tradeoff */
3649 grid
*g
= state
->game_grid
;
3650 int border
= BORDER(ds
->tilesize
);
3653 int redraw_everything
= FALSE
;
3655 int edges
[REDRAW_OBJECTS_LIMIT
], nedges
= 0;
3656 int faces
[REDRAW_OBJECTS_LIMIT
], nfaces
= 0;
3658 /* Redrawing is somewhat involved.
3660 * An update can theoretically affect an arbitrary number of edges
3661 * (consider, for example, completing or breaking a cycle which doesn't
3662 * satisfy all the clues -- we'll switch many edges between error and
3663 * normal states). On the other hand, redrawing the whole grid takes a
3664 * while, making the game feel sluggish, and many updates are actually
3665 * quite well localized.
3667 * This redraw algorithm attempts to cope with both situations gracefully
3668 * and correctly. For localized changes, we set a clip rectangle, fill
3669 * it with background, and then redraw (a plausible but conservative
3670 * guess at) the objects which intersect the rectangle; if several
3671 * objects need redrawing, we'll do them individually. However, if lots
3672 * of objects are affected, we'll just redraw everything.
3674 * The reason for all of this is that it's just not safe to do the redraw
3675 * piecemeal. If you try to draw an antialiased diagonal line over
3676 * itself, you get a slightly thicker antialiased diagonal line, which
3677 * looks rather ugly after a while.
3679 * So, we take two passes over the grid. The first attempts to work out
3680 * what needs doing, and the second actually does it.
3684 redraw_everything
= TRUE
;
3687 /* First, trundle through the faces. */
3688 for (i
= 0; i
< g
->num_faces
; i
++) {
3689 grid_face
*f
= g
->faces
+ i
;
3690 int sides
= f
->order
;
3693 int n
= state
->clues
[i
];
3697 clue_mistake
= (face_order(state
, i
, LINE_YES
) > n
||
3698 face_order(state
, i
, LINE_NO
) > (sides
-n
));
3699 clue_satisfied
= (face_order(state
, i
, LINE_YES
) == n
&&
3700 face_order(state
, i
, LINE_NO
) == (sides
-n
));
3702 if (clue_mistake
!= ds
->clue_error
[i
] ||
3703 clue_satisfied
!= ds
->clue_satisfied
[i
]) {
3704 ds
->clue_error
[i
] = clue_mistake
;
3705 ds
->clue_satisfied
[i
] = clue_satisfied
;
3706 if (nfaces
== REDRAW_OBJECTS_LIMIT
)
3707 redraw_everything
= TRUE
;
3709 faces
[nfaces
++] = i
;
3713 /* Work out what the flash state needs to be. */
3714 if (flashtime
> 0 &&
3715 (flashtime
<= FLASH_TIME
/3 ||
3716 flashtime
>= FLASH_TIME
*2/3)) {
3717 flash_changed
= !ds
->flashing
;
3718 ds
->flashing
= TRUE
;
3720 flash_changed
= ds
->flashing
;
3721 ds
->flashing
= FALSE
;
3724 /* Now, trundle through the edges. */
3725 for (i
= 0; i
< g
->num_edges
; i
++) {
3727 state
->line_errors
[i
] ? DS_LINE_ERROR
: state
->lines
[i
];
3728 if (new_ds
!= ds
->lines
[i
] ||
3729 (flash_changed
&& state
->lines
[i
] == LINE_YES
)) {
3730 ds
->lines
[i
] = new_ds
;
3731 if (nedges
== REDRAW_OBJECTS_LIMIT
)
3732 redraw_everything
= TRUE
;
3734 edges
[nedges
++] = i
;
3739 /* Pass one is now done. Now we do the actual drawing. */
3740 if (redraw_everything
) {
3741 int grid_width
= g
->highest_x
- g
->lowest_x
;
3742 int grid_height
= g
->highest_y
- g
->lowest_y
;
3743 int w
= grid_width
* ds
->tilesize
/ g
->tilesize
;
3744 int h
= grid_height
* ds
->tilesize
/ g
->tilesize
;
3746 game_redraw_in_rect(dr
, ds
, state
,
3747 0, 0, w
+ 2*border
+ 1, h
+ 2*border
+ 1);
3750 /* Right. Now we roll up our sleeves. */
3752 for (i
= 0; i
< nfaces
; i
++) {
3753 grid_face
*f
= g
->faces
+ faces
[i
];
3756 face_text_bbox(ds
, g
, f
, &x
, &y
, &w
, &h
);
3757 game_redraw_in_rect(dr
, ds
, state
, x
, y
, w
, h
);
3760 for (i
= 0; i
< nedges
; i
++) {
3761 grid_edge
*e
= g
->edges
+ edges
[i
];
3764 edge_bbox(ds
, g
, e
, &x
, &y
, &w
, &h
);
3765 game_redraw_in_rect(dr
, ds
, state
, x
, y
, w
, h
);
3772 static float game_flash_length(game_state
*oldstate
, game_state
*newstate
,
3773 int dir
, game_ui
*ui
)
3775 if (!oldstate
->solved
&& newstate
->solved
&&
3776 !oldstate
->cheated
&& !newstate
->cheated
) {
3783 static int game_status(game_state
*state
)
3785 return state
->solved ?
+1 : 0;
3788 static void game_print_size(game_params
*params
, float *x
, float *y
)
3793 * I'll use 7mm "squares" by default.
3795 game_compute_size(params
, 700, &pw
, &ph
);
3800 static void game_print(drawing
*dr
, game_state
*state
, int tilesize
)
3802 int ink
= print_mono_colour(dr
, 0);
3804 game_drawstate ads
, *ds
= &ads
;
3805 grid
*g
= state
->game_grid
;
3807 ds
->tilesize
= tilesize
;
3808 ds
->textx
= snewn(g
->num_faces
, int);
3809 ds
->texty
= snewn(g
->num_faces
, int);
3810 for (i
= 0; i
< g
->num_faces
; i
++)
3811 ds
->textx
[i
] = ds
->texty
[i
] = -1;
3813 for (i
= 0; i
< g
->num_dots
; i
++) {
3815 grid_to_screen(ds
, g
, g
->dots
[i
].x
, g
->dots
[i
].y
, &x
, &y
);
3816 draw_circle(dr
, x
, y
, ds
->tilesize
/ 15, ink
, ink
);
3822 for (i
= 0; i
< g
->num_faces
; i
++) {
3823 grid_face
*f
= g
->faces
+ i
;
3824 int clue
= state
->clues
[i
];
3828 c
[0] = CLUE2CHAR(clue
);
3830 face_text_pos(ds
, g
, f
, &x
, &y
);
3832 FONT_VARIABLE
, ds
->tilesize
/ 2,
3833 ALIGN_VCENTRE
| ALIGN_HCENTRE
, ink
, c
);
3840 for (i
= 0; i
< g
->num_edges
; i
++) {
3841 int thickness
= (state
->lines
[i
] == LINE_YES
) ?
30 : 150;
3842 grid_edge
*e
= g
->edges
+ i
;
3844 grid_to_screen(ds
, g
, e
->dot1
->x
, e
->dot1
->y
, &x1
, &y1
);
3845 grid_to_screen(ds
, g
, e
->dot2
->x
, e
->dot2
->y
, &x2
, &y2
);
3846 if (state
->lines
[i
] == LINE_YES
)
3848 /* (dx, dy) points from (x1, y1) to (x2, y2).
3849 * The line is then "fattened" in a perpendicular
3850 * direction to create a thin rectangle. */
3851 double d
= sqrt(SQ((double)x1
- x2
) + SQ((double)y1
- y2
));
3852 double dx
= (x2
- x1
) / d
;
3853 double dy
= (y2
- y1
) / d
;
3856 dx
= (dx
* ds
->tilesize
) / thickness
;
3857 dy
= (dy
* ds
->tilesize
) / thickness
;
3858 points
[0] = x1
+ (int)dy
;
3859 points
[1] = y1
- (int)dx
;
3860 points
[2] = x1
- (int)dy
;
3861 points
[3] = y1
+ (int)dx
;
3862 points
[4] = x2
- (int)dy
;
3863 points
[5] = y2
+ (int)dx
;
3864 points
[6] = x2
+ (int)dy
;
3865 points
[7] = y2
- (int)dx
;
3866 draw_polygon(dr
, points
, 4, ink
, ink
);
3870 /* Draw a dotted line */
3873 for (j
= 1; j
< divisions
; j
++) {
3874 /* Weighted average */
3875 int x
= (x1
* (divisions
-j
) + x2
* j
) / divisions
;
3876 int y
= (y1
* (divisions
-j
) + y2
* j
) / divisions
;
3877 draw_circle(dr
, x
, y
, ds
->tilesize
/ thickness
, ink
, ink
);
3887 #define thegame loopy
3890 const struct game thegame
= {
3891 "Loopy", "games.loopy", "loopy",
3898 TRUE
, game_configure
, custom_params
,
3906 TRUE
, game_can_format_as_text_now
, game_text_format
,
3914 PREFERRED_TILE_SIZE
, game_compute_size
, game_set_size
,
3917 game_free_drawstate
,
3922 TRUE
, FALSE
, game_print_size
, game_print
,
3923 FALSE
/* wants_statusbar */,
3924 FALSE
, game_timing_state
,
3925 0, /* mouse_priorities */
3928 #ifdef STANDALONE_SOLVER
3931 * Half-hearted standalone solver. It can't output the solution to
3932 * anything but a square puzzle, and it can't log the deductions
3933 * it makes either. But it can solve square puzzles, and more
3934 * importantly it can use its solver to grade the difficulty of
3935 * any puzzle you give it.
3940 int main(int argc
, char **argv
)
3944 char *id
= NULL
, *desc
, *err
;
3947 #if 0 /* verbose solver not supported here (yet) */
3948 int really_verbose
= FALSE
;
3951 while (--argc
> 0) {
3953 #if 0 /* verbose solver not supported here (yet) */
3954 if (!strcmp(p
, "-v")) {
3955 really_verbose
= TRUE
;
3958 if (!strcmp(p
, "-g")) {
3960 } else if (*p
== '-') {
3961 fprintf(stderr
, "%s: unrecognised option `%s'\n", argv
[0], p
);
3969 fprintf(stderr
, "usage: %s [-g | -v] <game_id>\n", argv
[0]);
3973 desc
= strchr(id
, ':');
3975 fprintf(stderr
, "%s: game id expects a colon in it\n", argv
[0]);
3980 p
= default_params();
3981 decode_params(p
, id
);
3982 err
= validate_desc(p
, desc
);
3984 fprintf(stderr
, "%s: %s\n", argv
[0], err
);
3987 s
= new_game(NULL
, p
, desc
);
3990 * When solving an Easy puzzle, we don't want to bother the
3991 * user with Hard-level deductions. For this reason, we grade
3992 * the puzzle internally before doing anything else.
3994 ret
= -1; /* placate optimiser */
3995 for (diff
= 0; diff
< DIFF_MAX
; diff
++) {
3996 solver_state
*sstate_new
;
3997 solver_state
*sstate
= new_solver_state((game_state
*)s
, diff
);
3999 sstate_new
= solve_game_rec(sstate
);
4001 if (sstate_new
->solver_status
== SOLVER_MISTAKE
)
4003 else if (sstate_new
->solver_status
== SOLVER_SOLVED
)
4008 free_solver_state(sstate_new
);
4009 free_solver_state(sstate
);
4015 if (diff
== DIFF_MAX
) {
4017 printf("Difficulty rating: harder than Hard, or ambiguous\n");
4019 printf("Unable to find a unique solution\n");
4023 printf("Difficulty rating: impossible (no solution exists)\n");
4025 printf("Difficulty rating: %s\n", diffnames
[diff
]);
4027 solver_state
*sstate_new
;
4028 solver_state
*sstate
= new_solver_state((game_state
*)s
, diff
);
4030 /* If we supported a verbose solver, we'd set verbosity here */
4032 sstate_new
= solve_game_rec(sstate
);
4034 if (sstate_new
->solver_status
== SOLVER_MISTAKE
)
4035 printf("Puzzle is inconsistent\n");
4037 assert(sstate_new
->solver_status
== SOLVER_SOLVED
);
4038 if (s
->grid_type
== 0) {
4039 fputs(game_text_format(sstate_new
->state
), stdout
);
4041 printf("Unable to output non-square grids\n");
4045 free_solver_state(sstate_new
);
4046 free_solver_state(sstate
);
4055 /* vim: set shiftwidth=4 tabstop=8: */