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.
85 /* Debugging options */
93 /* ----------------------------------------------------------------------
94 * Struct, enum and function declarations
110 /* Put -1 in a face that doesn't get a clue */
113 /* Array of line states, to store whether each line is
114 * YES, NO or UNKNOWN */
117 unsigned char *line_errors
;
122 /* Used in game_text_format(), so that it knows what type of
123 * grid it's trying to render as ASCII text. */
128 SOLVER_SOLVED
, /* This is the only solution the solver could find */
129 SOLVER_MISTAKE
, /* This is definitely not a solution */
130 SOLVER_AMBIGUOUS
, /* This _might_ be an ambiguous solution */
131 SOLVER_INCOMPLETE
/* This may be a partial solution */
134 /* ------ Solver state ------ */
135 typedef struct normal
{
136 /* For each dline, store a bitmask for whether we know:
137 * (bit 0) at least one is YES
138 * (bit 1) at most one is YES */
142 typedef struct hard
{
146 typedef struct solver_state
{
148 enum solver_status solver_status
;
149 /* NB looplen is the number of dots that are joined together at a point, ie a
150 * looplen of 1 means there are no lines to a particular dot */
156 char *face_yes_count
;
158 char *dot_solved
, *face_solved
;
161 normal_mode_state
*normal
;
162 hard_mode_state
*hard
;
166 * Difficulty levels. I do some macro ickery here to ensure that my
167 * enum and the various forms of my name list always match up.
170 #define DIFFLIST(A) \
171 A(EASY,Easy,e,easy_mode_deductions) \
172 A(NORMAL,Normal,n,normal_mode_deductions) \
173 A(HARD,Hard,h,hard_mode_deductions)
174 #define ENUM(upper,title,lower,fn) DIFF_ ## upper,
175 #define TITLE(upper,title,lower,fn) #title,
176 #define ENCODE(upper,title,lower,fn) #lower
177 #define CONFIG(upper,title,lower,fn) ":" #title
178 #define SOLVER_FN_DECL(upper,title,lower,fn) static int fn(solver_state *);
179 #define SOLVER_FN(upper,title,lower,fn) &fn,
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)
184 DIFFLIST(SOLVER_FN_DECL
)
185 static int (*(solver_fns
[]))(solver_state
*) = { DIFFLIST(SOLVER_FN
) };
192 /* Grid generation is expensive, so keep a (ref-counted) reference to the
193 * grid for these parameters, and only generate when required. */
197 /* line_drawstate is the same as line_state, but with the extra ERROR
198 * possibility. The drawing code copies line_state to line_drawstate,
199 * except in the case that the line is an error. */
200 enum line_state
{ LINE_YES
, LINE_UNKNOWN
, LINE_NO
};
201 enum line_drawstate
{ DS_LINE_YES
, DS_LINE_UNKNOWN
,
202 DS_LINE_NO
, DS_LINE_ERROR
};
204 #define OPP(line_state) \
208 struct game_drawstate
{
214 char *clue_satisfied
;
217 static char *validate_desc(game_params
*params
, char *desc
);
218 static int dot_order(const game_state
* state
, int i
, char line_type
);
219 static int face_order(const game_state
* state
, int i
, char line_type
);
220 static solver_state
*solve_game_rec(const solver_state
*sstate
,
224 static void check_caches(const solver_state
* sstate
);
226 #define check_caches(s)
229 /* ------- List of grid generators ------- */
230 #define GRIDLIST(A) \
231 A(Squares,grid_new_square,3,3) \
232 A(Triangular,grid_new_triangular,3,3) \
233 A(Honeycomb,grid_new_honeycomb,3,3) \
234 A(Snub-Square,grid_new_snubsquare,3,3) \
235 A(Cairo,grid_new_cairo,3,4) \
236 A(Great-Hexagonal,grid_new_greathexagonal,3,3) \
237 A(Octagonal,grid_new_octagonal,3,3) \
238 A(Kites,grid_new_kites,3,3)
240 #define GRID_NAME(title,fn,amin,omin) #title,
241 #define GRID_CONFIG(title,fn,amin,omin) ":" #title
242 #define GRID_FN(title,fn,amin,omin) &fn,
243 #define GRID_SIZES(title,fn,amin,omin) \
245 "Width and height for this grid type must both be at least " #amin, \
246 "At least one of width and height for this grid type must be at least " #omin,},
247 static char const *const gridnames
[] = { GRIDLIST(GRID_NAME
) };
248 #define GRID_CONFIGS GRIDLIST(GRID_CONFIG)
249 static grid
* (*(grid_fns
[]))(int w
, int h
) = { GRIDLIST(GRID_FN
) };
250 #define NUM_GRID_TYPES (sizeof(grid_fns) / sizeof(grid_fns[0]))
251 static const struct {
254 } grid_size_limits
[] = { GRIDLIST(GRID_SIZES
) };
256 /* Generates a (dynamically allocated) new grid, according to the
257 * type and size requested in params. Does nothing if the grid is already
258 * generated. The allocated grid is owned by the params object, and will be
259 * freed in free_params(). */
260 static void params_generate_grid(game_params
*params
)
262 if (!params
->game_grid
) {
263 params
->game_grid
= grid_fns
[params
->type
](params
->w
, params
->h
);
267 /* ----------------------------------------------------------------------
271 /* General constants */
272 #define PREFERRED_TILE_SIZE 32
273 #define BORDER(tilesize) ((tilesize) / 2)
274 #define FLASH_TIME 0.5F
276 #define BIT_SET(field, bit) ((field) & (1<<(bit)))
278 #define SET_BIT(field, bit) (BIT_SET(field, bit) ? FALSE : \
279 ((field) |= (1<<(bit)), TRUE))
281 #define CLEAR_BIT(field, bit) (BIT_SET(field, bit) ? \
282 ((field) &= ~(1<<(bit)), TRUE) : FALSE)
284 #define CLUE2CHAR(c) \
285 ((c < 0) ? ' ' : c + '0')
287 /* ----------------------------------------------------------------------
288 * General struct manipulation and other straightforward code
291 static game_state
*dup_game(game_state
*state
)
293 game_state
*ret
= snew(game_state
);
295 ret
->game_grid
= state
->game_grid
;
296 ret
->game_grid
->refcount
++;
298 ret
->solved
= state
->solved
;
299 ret
->cheated
= state
->cheated
;
301 ret
->clues
= snewn(state
->game_grid
->num_faces
, signed char);
302 memcpy(ret
->clues
, state
->clues
, state
->game_grid
->num_faces
);
304 ret
->lines
= snewn(state
->game_grid
->num_edges
, char);
305 memcpy(ret
->lines
, state
->lines
, state
->game_grid
->num_edges
);
307 ret
->line_errors
= snewn(state
->game_grid
->num_edges
, unsigned char);
308 memcpy(ret
->line_errors
, state
->line_errors
, state
->game_grid
->num_edges
);
310 ret
->grid_type
= state
->grid_type
;
314 static void free_game(game_state
*state
)
317 grid_free(state
->game_grid
);
320 sfree(state
->line_errors
);
325 static solver_state
*new_solver_state(game_state
*state
, int diff
) {
327 int num_dots
= state
->game_grid
->num_dots
;
328 int num_faces
= state
->game_grid
->num_faces
;
329 int num_edges
= state
->game_grid
->num_edges
;
330 solver_state
*ret
= snew(solver_state
);
332 ret
->state
= dup_game(state
);
334 ret
->solver_status
= SOLVER_INCOMPLETE
;
336 ret
->dotdsf
= snew_dsf(num_dots
);
337 ret
->looplen
= snewn(num_dots
, int);
339 for (i
= 0; i
< num_dots
; i
++) {
343 ret
->dot_solved
= snewn(num_dots
, char);
344 ret
->face_solved
= snewn(num_faces
, char);
345 memset(ret
->dot_solved
, FALSE
, num_dots
);
346 memset(ret
->face_solved
, FALSE
, num_faces
);
348 ret
->dot_yes_count
= snewn(num_dots
, char);
349 memset(ret
->dot_yes_count
, 0, num_dots
);
350 ret
->dot_no_count
= snewn(num_dots
, char);
351 memset(ret
->dot_no_count
, 0, num_dots
);
352 ret
->face_yes_count
= snewn(num_faces
, char);
353 memset(ret
->face_yes_count
, 0, num_faces
);
354 ret
->face_no_count
= snewn(num_faces
, char);
355 memset(ret
->face_no_count
, 0, num_faces
);
357 if (diff
< DIFF_NORMAL
) {
360 ret
->normal
= snew(normal_mode_state
);
361 ret
->normal
->dlines
= snewn(2*num_edges
, char);
362 memset(ret
->normal
->dlines
, 0, 2*num_edges
);
365 if (diff
< DIFF_HARD
) {
368 ret
->hard
= snew(hard_mode_state
);
369 ret
->hard
->linedsf
= snew_dsf(state
->game_grid
->num_edges
);
375 static void free_solver_state(solver_state
*sstate
) {
377 free_game(sstate
->state
);
378 sfree(sstate
->dotdsf
);
379 sfree(sstate
->looplen
);
380 sfree(sstate
->dot_solved
);
381 sfree(sstate
->face_solved
);
382 sfree(sstate
->dot_yes_count
);
383 sfree(sstate
->dot_no_count
);
384 sfree(sstate
->face_yes_count
);
385 sfree(sstate
->face_no_count
);
387 if (sstate
->normal
) {
388 sfree(sstate
->normal
->dlines
);
389 sfree(sstate
->normal
);
393 sfree(sstate
->hard
->linedsf
);
401 static solver_state
*dup_solver_state(const solver_state
*sstate
) {
402 game_state
*state
= sstate
->state
;
403 int num_dots
= state
->game_grid
->num_dots
;
404 int num_faces
= state
->game_grid
->num_faces
;
405 int num_edges
= state
->game_grid
->num_edges
;
406 solver_state
*ret
= snew(solver_state
);
408 ret
->state
= state
= dup_game(sstate
->state
);
410 ret
->solver_status
= sstate
->solver_status
;
412 ret
->dotdsf
= snewn(num_dots
, int);
413 ret
->looplen
= snewn(num_dots
, int);
414 memcpy(ret
->dotdsf
, sstate
->dotdsf
,
415 num_dots
* sizeof(int));
416 memcpy(ret
->looplen
, sstate
->looplen
,
417 num_dots
* sizeof(int));
419 ret
->dot_solved
= snewn(num_dots
, char);
420 ret
->face_solved
= snewn(num_faces
, char);
421 memcpy(ret
->dot_solved
, sstate
->dot_solved
, num_dots
);
422 memcpy(ret
->face_solved
, sstate
->face_solved
, num_faces
);
424 ret
->dot_yes_count
= snewn(num_dots
, char);
425 memcpy(ret
->dot_yes_count
, sstate
->dot_yes_count
, num_dots
);
426 ret
->dot_no_count
= snewn(num_dots
, char);
427 memcpy(ret
->dot_no_count
, sstate
->dot_no_count
, num_dots
);
429 ret
->face_yes_count
= snewn(num_faces
, char);
430 memcpy(ret
->face_yes_count
, sstate
->face_yes_count
, num_faces
);
431 ret
->face_no_count
= snewn(num_faces
, char);
432 memcpy(ret
->face_no_count
, sstate
->face_no_count
, num_faces
);
434 if (sstate
->normal
) {
435 ret
->normal
= snew(normal_mode_state
);
436 ret
->normal
->dlines
= snewn(2*num_edges
, char);
437 memcpy(ret
->normal
->dlines
, sstate
->normal
->dlines
,
444 ret
->hard
= snew(hard_mode_state
);
445 ret
->hard
->linedsf
= snewn(num_edges
, int);
446 memcpy(ret
->hard
->linedsf
, sstate
->hard
->linedsf
,
447 num_edges
* sizeof(int));
455 static game_params
*default_params(void)
457 game_params
*ret
= snew(game_params
);
466 ret
->diff
= DIFF_EASY
;
469 ret
->game_grid
= NULL
;
474 static game_params
*dup_params(game_params
*params
)
476 game_params
*ret
= snew(game_params
);
478 *ret
= *params
; /* structure copy */
479 if (ret
->game_grid
) {
480 ret
->game_grid
->refcount
++;
485 static const game_params presets
[] = {
487 { 7, 7, DIFF_EASY
, 0, NULL
},
488 { 7, 7, DIFF_NORMAL
, 0, NULL
},
489 { 7, 7, DIFF_HARD
, 0, NULL
},
490 { 7, 7, DIFF_HARD
, 1, NULL
},
491 { 7, 7, DIFF_HARD
, 2, NULL
},
492 { 5, 5, DIFF_HARD
, 3, NULL
},
493 { 7, 7, DIFF_HARD
, 4, NULL
},
494 { 5, 4, DIFF_HARD
, 5, NULL
},
495 { 5, 5, DIFF_HARD
, 6, NULL
},
496 { 5, 5, DIFF_HARD
, 7, NULL
},
498 { 7, 7, DIFF_EASY
, 0, NULL
},
499 { 10, 10, DIFF_EASY
, 0, NULL
},
500 { 7, 7, DIFF_NORMAL
, 0, NULL
},
501 { 10, 10, DIFF_NORMAL
, 0, NULL
},
502 { 7, 7, DIFF_HARD
, 0, NULL
},
503 { 10, 10, DIFF_HARD
, 0, NULL
},
504 { 10, 10, DIFF_HARD
, 1, NULL
},
505 { 12, 10, DIFF_HARD
, 2, NULL
},
506 { 7, 7, DIFF_HARD
, 3, NULL
},
507 { 9, 9, DIFF_HARD
, 4, NULL
},
508 { 5, 4, DIFF_HARD
, 5, NULL
},
509 { 7, 7, DIFF_HARD
, 6, NULL
},
510 { 5, 5, DIFF_HARD
, 7, NULL
},
514 static int game_fetch_preset(int i
, char **name
, game_params
**params
)
519 if (i
< 0 || i
>= lenof(presets
))
522 tmppar
= snew(game_params
);
523 *tmppar
= presets
[i
];
525 sprintf(buf
, "%dx%d %s - %s", tmppar
->h
, tmppar
->w
,
526 gridnames
[tmppar
->type
], diffnames
[tmppar
->diff
]);
532 static void free_params(game_params
*params
)
534 if (params
->game_grid
) {
535 grid_free(params
->game_grid
);
540 static void decode_params(game_params
*params
, char const *string
)
542 if (params
->game_grid
) {
543 grid_free(params
->game_grid
);
544 params
->game_grid
= NULL
;
546 params
->h
= params
->w
= atoi(string
);
547 params
->diff
= DIFF_EASY
;
548 while (*string
&& isdigit((unsigned char)*string
)) string
++;
549 if (*string
== 'x') {
551 params
->h
= atoi(string
);
552 while (*string
&& isdigit((unsigned char)*string
)) string
++;
554 if (*string
== 't') {
556 params
->type
= atoi(string
);
557 while (*string
&& isdigit((unsigned char)*string
)) string
++;
559 if (*string
== 'd') {
562 for (i
= 0; i
< DIFF_MAX
; i
++)
563 if (*string
== diffchars
[i
])
565 if (*string
) string
++;
569 static char *encode_params(game_params
*params
, int full
)
572 sprintf(str
, "%dx%dt%d", params
->w
, params
->h
, params
->type
);
574 sprintf(str
+ strlen(str
), "d%c", diffchars
[params
->diff
]);
578 static config_item
*game_configure(game_params
*params
)
583 ret
= snewn(5, config_item
);
585 ret
[0].name
= "Width";
586 ret
[0].type
= C_STRING
;
587 sprintf(buf
, "%d", params
->w
);
588 ret
[0].sval
= dupstr(buf
);
591 ret
[1].name
= "Height";
592 ret
[1].type
= C_STRING
;
593 sprintf(buf
, "%d", params
->h
);
594 ret
[1].sval
= dupstr(buf
);
597 ret
[2].name
= "Grid type";
598 ret
[2].type
= C_CHOICES
;
599 ret
[2].sval
= GRID_CONFIGS
;
600 ret
[2].ival
= params
->type
;
602 ret
[3].name
= "Difficulty";
603 ret
[3].type
= C_CHOICES
;
604 ret
[3].sval
= DIFFCONFIG
;
605 ret
[3].ival
= params
->diff
;
615 static game_params
*custom_params(config_item
*cfg
)
617 game_params
*ret
= snew(game_params
);
619 ret
->w
= atoi(cfg
[0].sval
);
620 ret
->h
= atoi(cfg
[1].sval
);
621 ret
->type
= cfg
[2].ival
;
622 ret
->diff
= cfg
[3].ival
;
624 ret
->game_grid
= NULL
;
628 static char *validate_params(game_params
*params
, int full
)
630 if (params
->type
< 0 || params
->type
>= NUM_GRID_TYPES
)
631 return "Illegal grid type";
632 if (params
->w
< grid_size_limits
[params
->type
].amin
||
633 params
->h
< grid_size_limits
[params
->type
].amin
)
634 return grid_size_limits
[params
->type
].aerr
;
635 if (params
->w
< grid_size_limits
[params
->type
].omin
&&
636 params
->h
< grid_size_limits
[params
->type
].omin
)
637 return grid_size_limits
[params
->type
].oerr
;
640 * This shouldn't be able to happen at all, since decode_params
641 * and custom_params will never generate anything that isn't
644 assert(params
->diff
< DIFF_MAX
);
649 /* Returns a newly allocated string describing the current puzzle */
650 static char *state_to_text(const game_state
*state
)
652 grid
*g
= state
->game_grid
;
654 int num_faces
= g
->num_faces
;
655 char *description
= snewn(num_faces
+ 1, char);
656 char *dp
= description
;
660 for (i
= 0; i
< num_faces
; i
++) {
661 if (state
->clues
[i
] < 0) {
662 if (empty_count
> 25) {
663 dp
+= sprintf(dp
, "%c", (int)(empty_count
+ 'a' - 1));
669 dp
+= sprintf(dp
, "%c", (int)(empty_count
+ 'a' - 1));
672 dp
+= sprintf(dp
, "%c", (int)CLUE2CHAR(state
->clues
[i
]));
677 dp
+= sprintf(dp
, "%c", (int)(empty_count
+ 'a' - 1));
679 retval
= dupstr(description
);
685 /* We require that the params pass the test in validate_params and that the
686 * description fills the entire game area */
687 static char *validate_desc(game_params
*params
, char *desc
)
691 params_generate_grid(params
);
692 g
= params
->game_grid
;
694 for (; *desc
; ++desc
) {
695 if (*desc
>= '0' && *desc
<= '9') {
700 count
+= *desc
- 'a' + 1;
703 return "Unknown character in description";
706 if (count
< g
->num_faces
)
707 return "Description too short for board size";
708 if (count
> g
->num_faces
)
709 return "Description too long for board size";
714 /* Sums the lengths of the numbers in range [0,n) */
715 /* See equivalent function in solo.c for justification of this. */
716 static int len_0_to_n(int n
)
718 int len
= 1; /* Counting 0 as a bit of a special case */
721 for (i
= 1; i
< n
; i
*= 10) {
722 len
+= max(n
- i
, 0);
728 static char *encode_solve_move(const game_state
*state
)
733 int num_edges
= state
->game_grid
->num_edges
;
735 /* This is going to return a string representing the moves needed to set
736 * every line in a grid to be the same as the ones in 'state'. The exact
737 * length of this string is predictable. */
739 len
= 1; /* Count the 'S' prefix */
740 /* Numbers in all lines */
741 len
+= len_0_to_n(num_edges
);
742 /* For each line we also have a letter */
745 ret
= snewn(len
+ 1, char);
748 p
+= sprintf(p
, "S");
750 for (i
= 0; i
< num_edges
; i
++) {
751 switch (state
->lines
[i
]) {
753 p
+= sprintf(p
, "%dy", i
);
756 p
+= sprintf(p
, "%dn", i
);
761 /* No point in doing sums like that if they're going to be wrong */
762 assert(strlen(ret
) <= (size_t)len
);
766 static game_ui
*new_ui(game_state
*state
)
771 static void free_ui(game_ui
*ui
)
775 static char *encode_ui(game_ui
*ui
)
780 static void decode_ui(game_ui
*ui
, char *encoding
)
784 static void game_changed_state(game_ui
*ui
, game_state
*oldstate
,
785 game_state
*newstate
)
789 static void game_compute_size(game_params
*params
, int tilesize
,
793 int grid_width
, grid_height
, rendered_width
, rendered_height
;
795 params_generate_grid(params
);
796 g
= params
->game_grid
;
797 grid_width
= g
->highest_x
- g
->lowest_x
;
798 grid_height
= g
->highest_y
- g
->lowest_y
;
799 /* multiply first to minimise rounding error on integer division */
800 rendered_width
= grid_width
* tilesize
/ g
->tilesize
;
801 rendered_height
= grid_height
* tilesize
/ g
->tilesize
;
802 *x
= rendered_width
+ 2 * BORDER(tilesize
) + 1;
803 *y
= rendered_height
+ 2 * BORDER(tilesize
) + 1;
806 static void game_set_size(drawing
*dr
, game_drawstate
*ds
,
807 game_params
*params
, int tilesize
)
809 ds
->tilesize
= tilesize
;
812 static float *game_colours(frontend
*fe
, int *ncolours
)
814 float *ret
= snewn(4 * NCOLOURS
, float);
816 frontend_default_colour(fe
, &ret
[COL_BACKGROUND
* 3]);
818 ret
[COL_FOREGROUND
* 3 + 0] = 0.0F
;
819 ret
[COL_FOREGROUND
* 3 + 1] = 0.0F
;
820 ret
[COL_FOREGROUND
* 3 + 2] = 0.0F
;
822 ret
[COL_LINEUNKNOWN
* 3 + 0] = 0.8F
;
823 ret
[COL_LINEUNKNOWN
* 3 + 1] = 0.8F
;
824 ret
[COL_LINEUNKNOWN
* 3 + 2] = 0.0F
;
826 ret
[COL_HIGHLIGHT
* 3 + 0] = 1.0F
;
827 ret
[COL_HIGHLIGHT
* 3 + 1] = 1.0F
;
828 ret
[COL_HIGHLIGHT
* 3 + 2] = 1.0F
;
830 ret
[COL_MISTAKE
* 3 + 0] = 1.0F
;
831 ret
[COL_MISTAKE
* 3 + 1] = 0.0F
;
832 ret
[COL_MISTAKE
* 3 + 2] = 0.0F
;
834 ret
[COL_SATISFIED
* 3 + 0] = 0.0F
;
835 ret
[COL_SATISFIED
* 3 + 1] = 0.0F
;
836 ret
[COL_SATISFIED
* 3 + 2] = 0.0F
;
838 *ncolours
= NCOLOURS
;
842 static game_drawstate
*game_new_drawstate(drawing
*dr
, game_state
*state
)
844 struct game_drawstate
*ds
= snew(struct game_drawstate
);
845 int num_faces
= state
->game_grid
->num_faces
;
846 int num_edges
= state
->game_grid
->num_edges
;
850 ds
->lines
= snewn(num_edges
, char);
851 ds
->clue_error
= snewn(num_faces
, char);
852 ds
->clue_satisfied
= snewn(num_faces
, char);
855 memset(ds
->lines
, LINE_UNKNOWN
, num_edges
);
856 memset(ds
->clue_error
, 0, num_faces
);
857 memset(ds
->clue_satisfied
, 0, num_faces
);
862 static void game_free_drawstate(drawing
*dr
, game_drawstate
*ds
)
864 sfree(ds
->clue_error
);
865 sfree(ds
->clue_satisfied
);
870 static int game_timing_state(game_state
*state
, game_ui
*ui
)
875 static float game_anim_length(game_state
*oldstate
, game_state
*newstate
,
876 int dir
, game_ui
*ui
)
881 static int game_can_format_as_text_now(game_params
*params
)
883 if (params
->type
!= 0)
888 static char *game_text_format(game_state
*state
)
894 grid
*g
= state
->game_grid
;
897 assert(state
->grid_type
== 0);
899 /* Work out the basic size unit */
900 f
= g
->faces
; /* first face */
901 assert(f
->order
== 4);
902 /* The dots are ordered clockwise, so the two opposite
903 * corners are guaranteed to span the square */
904 cell_size
= abs(f
->dots
[0]->x
- f
->dots
[2]->x
);
906 w
= (g
->highest_x
- g
->lowest_x
) / cell_size
;
907 h
= (g
->highest_y
- g
->lowest_y
) / cell_size
;
909 /* Create a blank "canvas" to "draw" on */
912 ret
= snewn(W
* H
+ 1, char);
913 for (y
= 0; y
< H
; y
++) {
914 for (x
= 0; x
< W
-1; x
++) {
917 ret
[y
*W
+ W
-1] = '\n';
921 /* Fill in edge info */
922 for (i
= 0; i
< g
->num_edges
; i
++) {
923 grid_edge
*e
= g
->edges
+ i
;
924 /* Cell coordinates, from (0,0) to (w-1,h-1) */
925 int x1
= (e
->dot1
->x
- g
->lowest_x
) / cell_size
;
926 int x2
= (e
->dot2
->x
- g
->lowest_x
) / cell_size
;
927 int y1
= (e
->dot1
->y
- g
->lowest_y
) / cell_size
;
928 int y2
= (e
->dot2
->y
- g
->lowest_y
) / cell_size
;
929 /* Midpoint, in canvas coordinates (canvas coordinates are just twice
930 * cell coordinates) */
933 switch (state
->lines
[i
]) {
935 ret
[y
*W
+ x
] = (y1
== y2
) ?
'-' : '|';
941 break; /* already a space */
943 assert(!"Illegal line state");
948 for (i
= 0; i
< g
->num_faces
; i
++) {
952 assert(f
->order
== 4);
953 /* Cell coordinates, from (0,0) to (w-1,h-1) */
954 x1
= (f
->dots
[0]->x
- g
->lowest_x
) / cell_size
;
955 x2
= (f
->dots
[2]->x
- g
->lowest_x
) / cell_size
;
956 y1
= (f
->dots
[0]->y
- g
->lowest_y
) / cell_size
;
957 y2
= (f
->dots
[2]->y
- g
->lowest_y
) / cell_size
;
958 /* Midpoint, in canvas coordinates */
961 ret
[y
*W
+ x
] = CLUE2CHAR(state
->clues
[i
]);
966 /* ----------------------------------------------------------------------
971 static void check_caches(const solver_state
* sstate
)
974 const game_state
*state
= sstate
->state
;
975 const grid
*g
= state
->game_grid
;
977 for (i
= 0; i
< g
->num_dots
; i
++) {
978 assert(dot_order(state
, i
, LINE_YES
) == sstate
->dot_yes_count
[i
]);
979 assert(dot_order(state
, i
, LINE_NO
) == sstate
->dot_no_count
[i
]);
982 for (i
= 0; i
< g
->num_faces
; i
++) {
983 assert(face_order(state
, i
, LINE_YES
) == sstate
->face_yes_count
[i
]);
984 assert(face_order(state
, i
, LINE_NO
) == sstate
->face_no_count
[i
]);
989 #define check_caches(s) \
991 fprintf(stderr, "check_caches at line %d\n", __LINE__); \
995 #endif /* DEBUG_CACHES */
997 /* ----------------------------------------------------------------------
998 * Solver utility functions
1001 /* Sets the line (with index i) to the new state 'line_new', and updates
1002 * the cached counts of any affected faces and dots.
1003 * Returns TRUE if this actually changed the line's state. */
1004 static int solver_set_line(solver_state
*sstate
, int i
,
1005 enum line_state line_new
1007 , const char *reason
1011 game_state
*state
= sstate
->state
;
1015 assert(line_new
!= LINE_UNKNOWN
);
1017 check_caches(sstate
);
1019 if (state
->lines
[i
] == line_new
) {
1020 return FALSE
; /* nothing changed */
1022 state
->lines
[i
] = line_new
;
1025 fprintf(stderr
, "solver: set line [%d] to %s (%s)\n",
1026 i
, line_new
== LINE_YES ?
"YES" : "NO",
1030 g
= state
->game_grid
;
1033 /* Update the cache for both dots and both faces affected by this. */
1034 if (line_new
== LINE_YES
) {
1035 sstate
->dot_yes_count
[e
->dot1
- g
->dots
]++;
1036 sstate
->dot_yes_count
[e
->dot2
- g
->dots
]++;
1038 sstate
->face_yes_count
[e
->face1
- g
->faces
]++;
1041 sstate
->face_yes_count
[e
->face2
- g
->faces
]++;
1044 sstate
->dot_no_count
[e
->dot1
- g
->dots
]++;
1045 sstate
->dot_no_count
[e
->dot2
- g
->dots
]++;
1047 sstate
->face_no_count
[e
->face1
- g
->faces
]++;
1050 sstate
->face_no_count
[e
->face2
- g
->faces
]++;
1054 check_caches(sstate
);
1059 #define solver_set_line(a, b, c) \
1060 solver_set_line(a, b, c, __FUNCTION__)
1064 * Merge two dots due to the existence of an edge between them.
1065 * Updates the dsf tracking equivalence classes, and keeps track of
1066 * the length of path each dot is currently a part of.
1067 * Returns TRUE if the dots were already linked, ie if they are part of a
1068 * closed loop, and false otherwise.
1070 static int merge_dots(solver_state
*sstate
, int edge_index
)
1073 grid
*g
= sstate
->state
->game_grid
;
1074 grid_edge
*e
= g
->edges
+ edge_index
;
1076 i
= e
->dot1
- g
->dots
;
1077 j
= e
->dot2
- g
->dots
;
1079 i
= dsf_canonify(sstate
->dotdsf
, i
);
1080 j
= dsf_canonify(sstate
->dotdsf
, j
);
1085 len
= sstate
->looplen
[i
] + sstate
->looplen
[j
];
1086 dsf_merge(sstate
->dotdsf
, i
, j
);
1087 i
= dsf_canonify(sstate
->dotdsf
, i
);
1088 sstate
->looplen
[i
] = len
;
1093 /* Merge two lines because the solver has deduced that they must be either
1094 * identical or opposite. Returns TRUE if this is new information, otherwise
1096 static int merge_lines(solver_state
*sstate
, int i
, int j
, int inverse
1098 , const char *reason
1104 assert(i
< sstate
->state
->game_grid
->num_edges
);
1105 assert(j
< sstate
->state
->game_grid
->num_edges
);
1107 i
= edsf_canonify(sstate
->hard
->linedsf
, i
, &inv_tmp
);
1109 j
= edsf_canonify(sstate
->hard
->linedsf
, j
, &inv_tmp
);
1112 edsf_merge(sstate
->hard
->linedsf
, i
, j
, inverse
);
1116 fprintf(stderr
, "%s [%d] [%d] %s(%s)\n",
1118 inverse ?
"inverse " : "", reason
);
1125 #define merge_lines(a, b, c, d) \
1126 merge_lines(a, b, c, d, __FUNCTION__)
1129 /* Count the number of lines of a particular type currently going into the
1131 static int dot_order(const game_state
* state
, int dot
, char line_type
)
1134 grid
*g
= state
->game_grid
;
1135 grid_dot
*d
= g
->dots
+ dot
;
1138 for (i
= 0; i
< d
->order
; i
++) {
1139 grid_edge
*e
= d
->edges
[i
];
1140 if (state
->lines
[e
- g
->edges
] == line_type
)
1146 /* Count the number of lines of a particular type currently surrounding the
1148 static int face_order(const game_state
* state
, int face
, char line_type
)
1151 grid
*g
= state
->game_grid
;
1152 grid_face
*f
= g
->faces
+ face
;
1155 for (i
= 0; i
< f
->order
; i
++) {
1156 grid_edge
*e
= f
->edges
[i
];
1157 if (state
->lines
[e
- g
->edges
] == line_type
)
1163 /* Set all lines bordering a dot of type old_type to type new_type
1164 * Return value tells caller whether this function actually did anything */
1165 static int dot_setall(solver_state
*sstate
, int dot
,
1166 char old_type
, char new_type
)
1168 int retval
= FALSE
, r
;
1169 game_state
*state
= sstate
->state
;
1174 if (old_type
== new_type
)
1177 g
= state
->game_grid
;
1180 for (i
= 0; i
< d
->order
; i
++) {
1181 int line_index
= d
->edges
[i
] - g
->edges
;
1182 if (state
->lines
[line_index
] == old_type
) {
1183 r
= solver_set_line(sstate
, line_index
, new_type
);
1191 /* Set all lines bordering a face of type old_type to type new_type */
1192 static int face_setall(solver_state
*sstate
, int face
,
1193 char old_type
, char new_type
)
1195 int retval
= FALSE
, r
;
1196 game_state
*state
= sstate
->state
;
1201 if (old_type
== new_type
)
1204 g
= state
->game_grid
;
1205 f
= g
->faces
+ face
;
1207 for (i
= 0; i
< f
->order
; i
++) {
1208 int line_index
= f
->edges
[i
] - g
->edges
;
1209 if (state
->lines
[line_index
] == old_type
) {
1210 r
= solver_set_line(sstate
, line_index
, new_type
);
1218 /* ----------------------------------------------------------------------
1219 * Loop generation and clue removal
1222 /* We're going to store a list of current candidate faces for lighting.
1223 * Each face gets a 'score', which tells us how adding that face right
1224 * now would affect the length of the solution loop. We're trying to
1225 * maximise that quantity so will bias our random selection of faces to
1226 * light towards those with high scores */
1229 unsigned long random
;
1233 static int get_face_cmpfn(void *v1
, void *v2
)
1235 struct face
*f1
= v1
;
1236 struct face
*f2
= v2
;
1237 /* These grid_face pointers always point into the same list of
1238 * 'grid_face's, so it's valid to subtract them. */
1239 return f1
->f
- f2
->f
;
1242 static int face_sort_cmpfn(void *v1
, void *v2
)
1244 struct face
*f1
= v1
;
1245 struct face
*f2
= v2
;
1248 r
= f2
->score
- f1
->score
;
1253 if (f1
->random
< f2
->random
)
1255 else if (f1
->random
> f2
->random
)
1259 * It's _just_ possible that two faces might have been given
1260 * the same random value. In that situation, fall back to
1261 * comparing based on the positions within the grid's face-list.
1262 * This introduces a tiny directional bias, but not a significant one.
1264 return get_face_cmpfn(f1
, f2
);
1267 enum { FACE_LIT
, FACE_UNLIT
};
1269 /* face should be of type grid_face* here. */
1270 #define FACE_LIT_STATE(face) \
1271 ( (face) == NULL ? FACE_UNLIT : \
1272 board[(face) - g->faces] )
1274 /* 'board' is an array of these enums, indicating which faces are
1275 * currently lit. Returns whether it's legal to light up the
1277 static int can_light_face(grid
*g
, char* board
, int face_index
)
1280 grid_face
*test_face
= g
->faces
+ face_index
;
1281 grid_face
*starting_face
, *current_face
;
1283 int current_state
, s
;
1284 int found_lit_neighbour
= FALSE
;
1285 assert(board
[face_index
] == FACE_UNLIT
);
1287 /* Can only consider a face for lighting if it's adjacent to an
1288 * already lit face. */
1289 for (i
= 0; i
< test_face
->order
; i
++) {
1290 grid_edge
*e
= test_face
->edges
[i
];
1291 grid_face
*f
= (e
->face1
== test_face
) ? e
->face2
: e
->face1
;
1292 if (FACE_LIT_STATE(f
) == FACE_LIT
) {
1293 found_lit_neighbour
= TRUE
;
1297 if (!found_lit_neighbour
)
1300 /* Need to avoid creating a loop of lit faces around some unlit faces.
1301 * Also need to avoid meeting another lit face at a corner, with
1302 * unlit faces in between. Here's a simple test that (I believe) takes
1303 * care of both these conditions:
1305 * Take the circular path formed by this face's edges, and inflate it
1306 * slightly outwards. Imagine walking around this path and consider
1307 * the faces that you visit in sequence. This will include all faces
1308 * touching the given face, either along an edge or just at a corner.
1309 * Count the number of LIT/UNLIT transitions you encounter, as you walk
1310 * along the complete loop. This will obviously turn out to be an even
1312 * If 0, we're either in a completely unlit zone, or this face is a hole
1313 * in a completely lit zone. If the former, we would create a brand new
1314 * island by lighting this face. And the latter ought to be impossible -
1315 * it would mean there's already a lit loop, so something went wrong
1317 * If 4 or greater, there are too many separate lit regions touching this
1318 * face, and lighting it up would create a loop or a corner-violation.
1319 * The only allowed case is when the count is exactly 2. */
1321 /* i points to a dot around the test face.
1322 * j points to a face around the i^th dot.
1323 * The current face will always be:
1324 * test_face->dots[i]->faces[j]
1325 * We assume dots go clockwise around the test face,
1326 * and faces go clockwise around dots. */
1328 starting_face
= test_face
->dots
[0]->faces
[0];
1329 if (starting_face
== test_face
) {
1331 starting_face
= test_face
->dots
[0]->faces
[1];
1333 current_face
= starting_face
;
1335 current_state
= FACE_LIT_STATE(current_face
);
1338 /* Advance to next face.
1339 * Need to loop here because it might take several goes to
1343 if (j
== test_face
->dots
[i
]->order
)
1346 if (test_face
->dots
[i
]->faces
[j
] == test_face
) {
1347 /* Advance to next dot round test_face, then
1348 * find current_face around new dot
1349 * and advance to the next face clockwise */
1351 if (i
== test_face
->order
)
1353 for (j
= 0; j
< test_face
->dots
[i
]->order
; j
++) {
1354 if (test_face
->dots
[i
]->faces
[j
] == current_face
)
1357 /* Must actually find current_face around new dot,
1358 * or else something's wrong with the grid. */
1359 assert(j
!= test_face
->dots
[i
]->order
);
1360 /* Found, so advance to next face and try again */
1365 /* (i,j) are now advanced to next face */
1366 current_face
= test_face
->dots
[i
]->faces
[j
];
1367 s
= FACE_LIT_STATE(current_face
);
1368 if (s
!= current_state
) {
1371 if (transitions
> 2)
1372 return FALSE
; /* no point in continuing */
1374 } while (current_face
!= starting_face
);
1376 return (transitions
== 2) ? TRUE
: FALSE
;
1379 /* The 'score' of a face reflects its current desirability for selection
1380 * as the next face to light. We want to encourage moving into uncharted
1381 * areas so we give scores according to how many of the face's neighbours
1382 * are currently unlit. */
1383 static int face_score(grid
*g
, char *board
, grid_face
*face
)
1385 /* Simple formula: score = neighbours unlit - neighbours lit */
1386 int lit_count
= 0, unlit_count
= 0;
1390 for (i
= 0; i
< face
->order
; i
++) {
1392 f
= (e
->face1
== face
) ? e
->face2
: e
->face1
;
1393 if (FACE_LIT_STATE(f
) == FACE_LIT
)
1398 return unlit_count
- lit_count
;
1401 /* Generate a new complete set of clues for the given game_state. */
1402 static void add_full_clues(game_state
*state
, random_state
*rs
)
1404 signed char *clues
= state
->clues
;
1406 grid
*g
= state
->game_grid
;
1408 int num_faces
= g
->num_faces
;
1409 int first_time
= TRUE
;
1411 struct face
*face
, *tmpface
;
1412 struct face face_pos
;
1414 /* These will contain exactly the same information, sorted into different
1416 tree234
*lightable_faces_sorted
, *lightable_faces_gettable
;
1418 #define IS_LIGHTING_CANDIDATE(i) \
1419 (board[i] == FACE_UNLIT && \
1420 can_light_face(g, board, i))
1422 board
= snewn(num_faces
, char);
1425 memset(board
, FACE_UNLIT
, num_faces
);
1427 /* We need a way of favouring faces that will increase our loopiness.
1428 * We do this by maintaining a list of all candidate faces sorted by
1429 * their score and choose randomly from that with appropriate skew.
1430 * In order to avoid consistently biasing towards particular faces, we
1431 * need the sort order _within_ each group of scores to be completely
1432 * random. But it would be abusing the hospitality of the tree234 data
1433 * structure if our comparison function were nondeterministic :-). So with
1434 * each face we associate a random number that does not change during a
1435 * particular run of the generator, and use that as a secondary sort key.
1436 * Yes, this means we will be biased towards particular random faces in
1437 * any one run but that doesn't actually matter. */
1439 lightable_faces_sorted
= newtree234(face_sort_cmpfn
);
1440 lightable_faces_gettable
= newtree234(get_face_cmpfn
);
1441 #define ADD_FACE(f) \
1443 struct face *x = add234(lightable_faces_sorted, f); \
1445 x = add234(lightable_faces_gettable, f); \
1449 #define REMOVE_FACE(f) \
1451 struct face *x = del234(lightable_faces_sorted, f); \
1453 x = del234(lightable_faces_gettable, f); \
1457 /* Light faces one at a time until the board is interesting enough */
1462 /* lightable_faces_xxx are empty, so start the process by
1463 * lighting up the middle face. These tree234s should
1464 * remain empty, consistent with what would happen if
1465 * first_time were FALSE. */
1466 board
[g
->middle_face
- g
->faces
] = FACE_LIT
;
1467 face
= snew(struct face
);
1468 face
->f
= g
->middle_face
;
1469 /* No need to initialise any more of 'face' here, no other fields
1470 * are used in this case. */
1472 /* We have count234(lightable_faces_gettable) possibilities, and in
1473 * lightable_faces_sorted they are sorted with the most desirable
1475 c
= count234(lightable_faces_sorted
);
1478 assert(c
== count234(lightable_faces_gettable
));
1480 /* Check that the best face available is any good */
1481 face
= (struct face
*)index234(lightable_faces_sorted
, 0);
1485 * The situation for a general grid is slightly different from
1486 * a square grid. Decreasing the perimeter should be allowed
1487 * sometimes (think about creating a hexagon of lit triangles,
1488 * for example). For if it were _never_ done, then the user would
1489 * be able to illicitly deduce certain things. So we do it
1490 * sometimes but not always.
1492 if (face
->score
<= 0 && random_upto(rs
, 2) == 0) {
1496 assert(face
->f
); /* not the infinite face */
1497 assert(FACE_LIT_STATE(face
->f
) == FACE_UNLIT
);
1499 /* Update data structures */
1500 /* Light up the face and remove it from the lists */
1501 board
[face
->f
- g
->faces
] = FACE_LIT
;
1505 /* The face we've just lit up potentially affects the lightability
1506 * of any neighbouring faces (touching at a corner or edge). So the
1507 * search needs to be conducted around all faces touching the one
1508 * we've just lit. Iterate over its corners, then over each corner's
1510 for (i
= 0; i
< face
->f
->order
; i
++) {
1511 grid_dot
*d
= face
->f
->dots
[i
];
1512 for (j
= 0; j
< d
->order
; j
++) {
1513 grid_face
*f2
= d
->faces
[j
];
1519 tmpface
= find234(lightable_faces_gettable
, &face_pos
, NULL
);
1521 assert(tmpface
->f
== face_pos
.f
);
1522 assert(FACE_LIT_STATE(tmpface
->f
) == FACE_UNLIT
);
1523 REMOVE_FACE(tmpface
);
1525 tmpface
= snew(struct face
);
1526 tmpface
->f
= face_pos
.f
;
1527 tmpface
->random
= random_bits(rs
, 31);
1529 tmpface
->score
= face_score(g
, board
, tmpface
->f
);
1531 if (IS_LIGHTING_CANDIDATE(tmpface
->f
- g
->faces
)) {
1542 while ((face
= delpos234(lightable_faces_gettable
, 0)) != NULL
)
1544 freetree234(lightable_faces_gettable
);
1545 freetree234(lightable_faces_sorted
);
1547 /* Fill out all the clues by initialising to 0, then iterating over
1548 * all edges and incrementing each clue as we find edges that border
1549 * between LIT/UNLIT faces */
1550 memset(clues
, 0, num_faces
);
1551 for (i
= 0; i
< g
->num_edges
; i
++) {
1552 grid_edge
*e
= g
->edges
+ i
;
1553 grid_face
*f1
= e
->face1
;
1554 grid_face
*f2
= e
->face2
;
1555 if (FACE_LIT_STATE(f1
) != FACE_LIT_STATE(f2
)) {
1556 if (f1
) clues
[f1
- g
->faces
]++;
1557 if (f2
) clues
[f2
- g
->faces
]++;
1565 static int game_has_unique_soln(const game_state
*state
, int diff
)
1568 solver_state
*sstate_new
;
1569 solver_state
*sstate
= new_solver_state((game_state
*)state
, diff
);
1571 sstate_new
= solve_game_rec(sstate
, diff
);
1573 assert(sstate_new
->solver_status
!= SOLVER_MISTAKE
);
1574 ret
= (sstate_new
->solver_status
== SOLVER_SOLVED
);
1576 free_solver_state(sstate_new
);
1577 free_solver_state(sstate
);
1583 /* Remove clues one at a time at random. */
1584 static game_state
*remove_clues(game_state
*state
, random_state
*rs
,
1588 int num_faces
= state
->game_grid
->num_faces
;
1589 game_state
*ret
= dup_game(state
), *saved_ret
;
1592 /* We need to remove some clues. We'll do this by forming a list of all
1593 * available clues, shuffling it, then going along one at a
1594 * time clearing each clue in turn for which doing so doesn't render the
1595 * board unsolvable. */
1596 face_list
= snewn(num_faces
, int);
1597 for (n
= 0; n
< num_faces
; ++n
) {
1601 shuffle(face_list
, num_faces
, sizeof(int), rs
);
1603 for (n
= 0; n
< num_faces
; ++n
) {
1604 saved_ret
= dup_game(ret
);
1605 ret
->clues
[face_list
[n
]] = -1;
1607 if (game_has_unique_soln(ret
, diff
)) {
1608 free_game(saved_ret
);
1620 static char *new_game_desc(game_params
*params
, random_state
*rs
,
1621 char **aux
, int interactive
)
1623 /* solution and description both use run-length encoding in obvious ways */
1626 game_state
*state
= snew(game_state
);
1627 game_state
*state_new
;
1628 params_generate_grid(params
);
1629 state
->game_grid
= g
= params
->game_grid
;
1631 state
->clues
= snewn(g
->num_faces
, signed char);
1632 state
->lines
= snewn(g
->num_edges
, char);
1633 state
->line_errors
= snewn(g
->num_edges
, unsigned char);
1635 state
->grid_type
= params
->type
;
1639 memset(state
->lines
, LINE_UNKNOWN
, g
->num_edges
);
1640 memset(state
->line_errors
, 0, g
->num_edges
);
1642 state
->solved
= state
->cheated
= FALSE
;
1644 /* Get a new random solvable board with all its clues filled in. Yes, this
1645 * can loop for ever if the params are suitably unfavourable, but
1646 * preventing games smaller than 4x4 seems to stop this happening */
1648 add_full_clues(state
, rs
);
1649 } while (!game_has_unique_soln(state
, params
->diff
));
1651 state_new
= remove_clues(state
, rs
, params
->diff
);
1656 if (params
->diff
> 0 && game_has_unique_soln(state
, params
->diff
-1)) {
1658 fprintf(stderr
, "Rejecting board, it is too easy\n");
1660 goto newboard_please
;
1663 retval
= state_to_text(state
);
1667 assert(!validate_desc(params
, retval
));
1672 static game_state
*new_game(midend
*me
, game_params
*params
, char *desc
)
1675 game_state
*state
= snew(game_state
);
1676 int empties_to_make
= 0;
1678 const char *dp
= desc
;
1680 int num_faces
, num_edges
;
1682 params_generate_grid(params
);
1683 state
->game_grid
= g
= params
->game_grid
;
1685 num_faces
= g
->num_faces
;
1686 num_edges
= g
->num_edges
;
1688 state
->clues
= snewn(num_faces
, signed char);
1689 state
->lines
= snewn(num_edges
, char);
1690 state
->line_errors
= snewn(num_edges
, unsigned char);
1692 state
->solved
= state
->cheated
= FALSE
;
1694 state
->grid_type
= params
->type
;
1696 for (i
= 0; i
< num_faces
; i
++) {
1697 if (empties_to_make
) {
1699 state
->clues
[i
] = -1;
1705 if (n
>= 0 && n
< 10) {
1706 state
->clues
[i
] = n
;
1710 state
->clues
[i
] = -1;
1711 empties_to_make
= n
- 1;
1716 memset(state
->lines
, LINE_UNKNOWN
, num_edges
);
1717 memset(state
->line_errors
, 0, num_edges
);
1721 /* Calculates the line_errors data, and checks if the current state is a
1723 static int check_completion(game_state
*state
)
1725 grid
*g
= state
->game_grid
;
1727 int num_faces
= g
->num_faces
;
1729 int infinite_area
, finite_area
;
1730 int loops_found
= 0;
1731 int found_edge_not_in_loop
= FALSE
;
1733 memset(state
->line_errors
, 0, g
->num_edges
);
1735 /* LL implementation of SGT's idea:
1736 * A loop will partition the grid into an inside and an outside.
1737 * If there is more than one loop, the grid will be partitioned into
1738 * even more distinct regions. We can therefore track equivalence of
1739 * faces, by saying that two faces are equivalent when there is a non-YES
1740 * edge between them.
1741 * We could keep track of the number of connected components, by counting
1742 * the number of dsf-merges that aren't no-ops.
1743 * But we're only interested in 3 separate cases:
1744 * no loops, one loop, more than one loop.
1746 * No loops: all faces are equivalent to the infinite face.
1747 * One loop: only two equivalence classes - finite and infinite.
1748 * >= 2 loops: there are 2 distinct finite regions.
1750 * So we simply make two passes through all the edges.
1751 * In the first pass, we dsf-merge the two faces bordering each non-YES
1753 * In the second pass, we look for YES-edges bordering:
1754 * a) two non-equivalent faces.
1755 * b) two non-equivalent faces, and one of them is part of a different
1756 * finite area from the first finite area we've seen.
1758 * An occurrence of a) means there is at least one loop.
1759 * An occurrence of b) means there is more than one loop.
1760 * Edges satisfying a) are marked as errors.
1762 * While we're at it, we set a flag if we find a YES edge that is not
1764 * This information will help decide, if there's a single loop, whether it
1765 * is a candidate for being a solution (that is, all YES edges are part of
1768 * If there is a candidate loop, we then go through all clues and check
1769 * they are all satisfied. If so, we have found a solution and we can
1770 * unmark all line_errors.
1773 /* Infinite face is at the end - its index is num_faces.
1774 * This macro is just to make this obvious! */
1775 #define INF_FACE num_faces
1776 dsf
= snewn(num_faces
+ 1, int);
1777 dsf_init(dsf
, num_faces
+ 1);
1780 for (i
= 0; i
< g
->num_edges
; i
++) {
1781 grid_edge
*e
= g
->edges
+ i
;
1782 int f1
= e
->face1 ? e
->face1
- g
->faces
: INF_FACE
;
1783 int f2
= e
->face2 ? e
->face2
- g
->faces
: INF_FACE
;
1784 if (state
->lines
[i
] != LINE_YES
)
1785 dsf_merge(dsf
, f1
, f2
);
1789 infinite_area
= dsf_canonify(dsf
, INF_FACE
);
1791 for (i
= 0; i
< g
->num_edges
; i
++) {
1792 grid_edge
*e
= g
->edges
+ i
;
1793 int f1
= e
->face1 ? e
->face1
- g
->faces
: INF_FACE
;
1794 int can1
= dsf_canonify(dsf
, f1
);
1795 int f2
= e
->face2 ? e
->face2
- g
->faces
: INF_FACE
;
1796 int can2
= dsf_canonify(dsf
, f2
);
1797 if (state
->lines
[i
] != LINE_YES
) continue;
1800 /* Faces are equivalent, so this edge not part of a loop */
1801 found_edge_not_in_loop
= TRUE
;
1804 state
->line_errors
[i
] = TRUE
;
1805 if (loops_found
== 0) loops_found
= 1;
1807 /* Don't bother with further checks if we've already found 2 loops */
1808 if (loops_found
== 2) continue;
1810 if (finite_area
== -1) {
1811 /* Found our first finite area */
1812 if (can1
!= infinite_area
)
1818 /* Have we found a second area? */
1819 if (finite_area
!= -1) {
1820 if (can1
!= infinite_area
&& can1
!= finite_area
) {
1824 if (can2
!= infinite_area
&& can2
!= finite_area
) {
1831 printf("loops_found = %d\n", loops_found);
1832 printf("found_edge_not_in_loop = %s\n",
1833 found_edge_not_in_loop ? "TRUE" : "FALSE");
1836 sfree(dsf
); /* No longer need the dsf */
1838 /* Have we found a candidate loop? */
1839 if (loops_found
== 1 && !found_edge_not_in_loop
) {
1840 /* Yes, so check all clues are satisfied */
1841 int found_clue_violation
= FALSE
;
1842 for (i
= 0; i
< num_faces
; i
++) {
1843 int c
= state
->clues
[i
];
1845 if (face_order(state
, i
, LINE_YES
) != c
) {
1846 found_clue_violation
= TRUE
;
1852 if (!found_clue_violation
) {
1853 /* The loop is good */
1854 memset(state
->line_errors
, 0, g
->num_edges
);
1855 return TRUE
; /* No need to bother checking for dot violations */
1859 /* Check for dot violations */
1860 for (i
= 0; i
< g
->num_dots
; i
++) {
1861 int yes
= dot_order(state
, i
, LINE_YES
);
1862 int unknown
= dot_order(state
, i
, LINE_UNKNOWN
);
1863 if ((yes
== 1 && unknown
== 0) || (yes
>= 3)) {
1864 /* violation, so mark all YES edges as errors */
1865 grid_dot
*d
= g
->dots
+ i
;
1867 for (j
= 0; j
< d
->order
; j
++) {
1868 int e
= d
->edges
[j
] - g
->edges
;
1869 if (state
->lines
[e
] == LINE_YES
)
1870 state
->line_errors
[e
] = TRUE
;
1877 /* ----------------------------------------------------------------------
1880 * Our solver modes operate as follows. Each mode also uses the modes above it.
1883 * Just implement the rules of the game.
1886 * For each (adjacent) pair of lines through each dot we store a bit for
1887 * whether at least one of them is on and whether at most one is on. (If we
1888 * know both or neither is on that's already stored more directly.)
1891 * Use edsf data structure to make equivalence classes of lines that are
1892 * known identical to or opposite to one another.
1897 * For general grids, we consider "dlines" to be pairs of lines joined
1898 * at a dot. The lines must be adjacent around the dot, so we can think of
1899 * a dline as being a dot+face combination. Or, a dot+edge combination where
1900 * the second edge is taken to be the next clockwise edge from the dot.
1901 * Original loopy code didn't have this extra restriction of the lines being
1902 * adjacent. From my tests with square grids, this extra restriction seems to
1903 * take little, if anything, away from the quality of the puzzles.
1904 * A dline can be uniquely identified by an edge/dot combination, given that
1905 * a dline-pair always goes clockwise around its common dot. The edge/dot
1906 * combination can be represented by an edge/bool combination - if bool is
1907 * TRUE, use edge->dot1 else use edge->dot2. So the total number of dlines is
1908 * exactly twice the number of edges in the grid - although the dlines
1909 * spanning the infinite face are not all that useful to the solver.
1910 * Note that, by convention, a dline goes clockwise around its common dot,
1911 * which means the dline goes anti-clockwise around its common face.
1914 /* Helper functions for obtaining an index into an array of dlines, given
1915 * various information. We assume the grid layout conventions about how
1916 * the various lists are interleaved - see grid_make_consistent() for
1919 /* i points to the first edge of the dline pair, reading clockwise around
1921 static int dline_index_from_dot(grid
*g
, grid_dot
*d
, int i
)
1923 grid_edge
*e
= d
->edges
[i
];
1928 if (i2
== d
->order
) i2
= 0;
1931 ret
= 2 * (e
- g
->edges
) + ((e
->dot1
== d
) ?
1 : 0);
1933 printf("dline_index_from_dot: d=%d,i=%d, edges [%d,%d] - %d\n",
1934 (int)(d
- g
->dots
), i
, (int)(e
- g
->edges
),
1935 (int)(e2
- g
->edges
), ret
);
1939 /* i points to the second edge of the dline pair, reading clockwise around
1940 * the face. That is, the edges of the dline, starting at edge{i}, read
1941 * anti-clockwise around the face. By layout conventions, the common dot
1942 * of the dline will be f->dots[i] */
1943 static int dline_index_from_face(grid
*g
, grid_face
*f
, int i
)
1945 grid_edge
*e
= f
->edges
[i
];
1946 grid_dot
*d
= f
->dots
[i
];
1951 if (i2
< 0) i2
+= f
->order
;
1954 ret
= 2 * (e
- g
->edges
) + ((e
->dot1
== d
) ?
1 : 0);
1956 printf("dline_index_from_face: f=%d,i=%d, edges [%d,%d] - %d\n",
1957 (int)(f
- g
->faces
), i
, (int)(e
- g
->edges
),
1958 (int)(e2
- g
->edges
), ret
);
1962 static int is_atleastone(const char *dline_array
, int index
)
1964 return BIT_SET(dline_array
[index
], 0);
1966 static int set_atleastone(char *dline_array
, int index
)
1968 return SET_BIT(dline_array
[index
], 0);
1970 static int is_atmostone(const char *dline_array
, int index
)
1972 return BIT_SET(dline_array
[index
], 1);
1974 static int set_atmostone(char *dline_array
, int index
)
1976 return SET_BIT(dline_array
[index
], 1);
1979 static void array_setall(char *array
, char from
, char to
, int len
)
1981 char *p
= array
, *p_old
= p
;
1982 int len_remaining
= len
;
1984 while ((p
= memchr(p
, from
, len_remaining
))) {
1986 len_remaining
-= p
- p_old
;
1991 /* Helper, called when doing dline dot deductions, in the case where we
1992 * have 4 UNKNOWNs, and two of them (adjacent) have *exactly* one YES between
1993 * them (because of dline atmostone/atleastone).
1994 * On entry, edge points to the first of these two UNKNOWNs. This function
1995 * will find the opposite UNKNOWNS (if they are adjacent to one another)
1996 * and set their corresponding dline to atleastone. (Setting atmostone
1997 * already happens in earlier dline deductions) */
1998 static int dline_set_opp_atleastone(solver_state
*sstate
,
1999 grid_dot
*d
, int edge
)
2001 game_state
*state
= sstate
->state
;
2002 grid
*g
= state
->game_grid
;
2005 for (opp
= 0; opp
< N
; opp
++) {
2006 int opp_dline_index
;
2007 if (opp
== edge
|| opp
== edge
+1 || opp
== edge
-1)
2009 if (opp
== 0 && edge
== N
-1)
2011 if (opp
== N
-1 && edge
== 0)
2014 if (opp2
== N
) opp2
= 0;
2015 /* Check if opp, opp2 point to LINE_UNKNOWNs */
2016 if (state
->lines
[d
->edges
[opp
] - g
->edges
] != LINE_UNKNOWN
)
2018 if (state
->lines
[d
->edges
[opp2
] - g
->edges
] != LINE_UNKNOWN
)
2020 /* Found opposite UNKNOWNS and they're next to each other */
2021 opp_dline_index
= dline_index_from_dot(g
, d
, opp
);
2022 return set_atleastone(sstate
->normal
->dlines
, opp_dline_index
);
2028 /* Set pairs of lines around this face which are known to be identical, to
2029 * the given line_state */
2030 static int face_setall_identical(solver_state
*sstate
, int face_index
,
2031 enum line_state line_new
)
2033 /* can[dir] contains the canonical line associated with the line in
2034 * direction dir from the square in question. Similarly inv[dir] is
2035 * whether or not the line in question is inverse to its canonical
2038 game_state
*state
= sstate
->state
;
2039 grid
*g
= state
->game_grid
;
2040 grid_face
*f
= g
->faces
+ face_index
;
2043 int can1
, can2
, inv1
, inv2
;
2045 for (i
= 0; i
< N
; i
++) {
2046 int line1_index
= f
->edges
[i
] - g
->edges
;
2047 if (state
->lines
[line1_index
] != LINE_UNKNOWN
)
2049 for (j
= i
+ 1; j
< N
; j
++) {
2050 int line2_index
= f
->edges
[j
] - g
->edges
;
2051 if (state
->lines
[line2_index
] != LINE_UNKNOWN
)
2054 /* Found two UNKNOWNS */
2055 can1
= edsf_canonify(sstate
->hard
->linedsf
, line1_index
, &inv1
);
2056 can2
= edsf_canonify(sstate
->hard
->linedsf
, line2_index
, &inv2
);
2057 if (can1
== can2
&& inv1
== inv2
) {
2058 solver_set_line(sstate
, line1_index
, line_new
);
2059 solver_set_line(sstate
, line2_index
, line_new
);
2066 /* Given a dot or face, and a count of LINE_UNKNOWNs, find them and
2067 * return the edge indices into e. */
2068 static void find_unknowns(game_state
*state
,
2069 grid_edge
**edge_list
, /* Edge list to search (from a face or a dot) */
2070 int expected_count
, /* Number of UNKNOWNs (comes from solver's cache) */
2071 int *e
/* Returned edge indices */)
2074 grid
*g
= state
->game_grid
;
2075 while (c
< expected_count
) {
2076 int line_index
= *edge_list
- g
->edges
;
2077 if (state
->lines
[line_index
] == LINE_UNKNOWN
) {
2085 /* If we have a list of edges, and we know whether the number of YESs should
2086 * be odd or even, and there are only a few UNKNOWNs, we can do some simple
2087 * linedsf deductions. This can be used for both face and dot deductions.
2088 * Returns the difficulty level of the next solver that should be used,
2089 * or DIFF_MAX if no progress was made. */
2090 static int parity_deductions(solver_state
*sstate
,
2091 grid_edge
**edge_list
, /* Edge list (from a face or a dot) */
2092 int total_parity
, /* Expected number of YESs modulo 2 (either 0 or 1) */
2095 game_state
*state
= sstate
->state
;
2096 int diff
= DIFF_MAX
;
2097 int *linedsf
= sstate
->hard
->linedsf
;
2099 if (unknown_count
== 2) {
2100 /* Lines are known alike/opposite, depending on inv. */
2102 find_unknowns(state
, edge_list
, 2, e
);
2103 if (merge_lines(sstate
, e
[0], e
[1], total_parity
))
2104 diff
= min(diff
, DIFF_HARD
);
2105 } else if (unknown_count
== 3) {
2107 int can
[3]; /* canonical edges */
2108 int inv
[3]; /* whether can[x] is inverse to e[x] */
2109 find_unknowns(state
, edge_list
, 3, e
);
2110 can
[0] = edsf_canonify(linedsf
, e
[0], inv
);
2111 can
[1] = edsf_canonify(linedsf
, e
[1], inv
+1);
2112 can
[2] = edsf_canonify(linedsf
, e
[2], inv
+2);
2113 if (can
[0] == can
[1]) {
2114 if (solver_set_line(sstate
, e
[2], (total_parity
^inv
[0]^inv
[1]) ?
2115 LINE_YES
: LINE_NO
))
2116 diff
= min(diff
, DIFF_EASY
);
2118 if (can
[0] == can
[2]) {
2119 if (solver_set_line(sstate
, e
[1], (total_parity
^inv
[0]^inv
[2]) ?
2120 LINE_YES
: LINE_NO
))
2121 diff
= min(diff
, DIFF_EASY
);
2123 if (can
[1] == can
[2]) {
2124 if (solver_set_line(sstate
, e
[0], (total_parity
^inv
[1]^inv
[2]) ?
2125 LINE_YES
: LINE_NO
))
2126 diff
= min(diff
, DIFF_EASY
);
2128 } else if (unknown_count
== 4) {
2130 int can
[4]; /* canonical edges */
2131 int inv
[4]; /* whether can[x] is inverse to e[x] */
2132 find_unknowns(state
, edge_list
, 4, e
);
2133 can
[0] = edsf_canonify(linedsf
, e
[0], inv
);
2134 can
[1] = edsf_canonify(linedsf
, e
[1], inv
+1);
2135 can
[2] = edsf_canonify(linedsf
, e
[2], inv
+2);
2136 can
[3] = edsf_canonify(linedsf
, e
[3], inv
+3);
2137 if (can
[0] == can
[1]) {
2138 if (merge_lines(sstate
, e
[2], e
[3], total_parity
^inv
[0]^inv
[1]))
2139 diff
= min(diff
, DIFF_HARD
);
2140 } else if (can
[0] == can
[2]) {
2141 if (merge_lines(sstate
, e
[1], e
[3], total_parity
^inv
[0]^inv
[2]))
2142 diff
= min(diff
, DIFF_HARD
);
2143 } else if (can
[0] == can
[3]) {
2144 if (merge_lines(sstate
, e
[1], e
[2], total_parity
^inv
[0]^inv
[3]))
2145 diff
= min(diff
, DIFF_HARD
);
2146 } else if (can
[1] == can
[2]) {
2147 if (merge_lines(sstate
, e
[0], e
[3], total_parity
^inv
[1]^inv
[2]))
2148 diff
= min(diff
, DIFF_HARD
);
2149 } else if (can
[1] == can
[3]) {
2150 if (merge_lines(sstate
, e
[0], e
[2], total_parity
^inv
[1]^inv
[3]))
2151 diff
= min(diff
, DIFF_HARD
);
2152 } else if (can
[2] == can
[3]) {
2153 if (merge_lines(sstate
, e
[0], e
[1], total_parity
^inv
[2]^inv
[3]))
2154 diff
= min(diff
, DIFF_HARD
);
2162 * These are the main solver functions.
2164 * Their return values are diff values corresponding to the lowest mode solver
2165 * that would notice the work that they have done. For example if the normal
2166 * mode solver adds actual lines or crosses, it will return DIFF_EASY as the
2167 * easy mode solver might be able to make progress using that. It doesn't make
2168 * sense for one of them to return a diff value higher than that of the
2171 * Each function returns the lowest value it can, as early as possible, in
2172 * order to try and pass as much work as possible back to the lower level
2173 * solvers which progress more quickly.
2176 /* PROPOSED NEW DESIGN:
2177 * We have a work queue consisting of 'events' notifying us that something has
2178 * happened that a particular solver mode might be interested in. For example
2179 * the hard mode solver might do something that helps the normal mode solver at
2180 * dot [x,y] in which case it will enqueue an event recording this fact. Then
2181 * we pull events off the work queue, and hand each in turn to the solver that
2182 * is interested in them. If a solver reports that it failed we pass the same
2183 * event on to progressively more advanced solvers and the loop detector. Once
2184 * we've exhausted an event, or it has helped us progress, we drop it and
2185 * continue to the next one. The events are sorted first in order of solver
2186 * complexity (easy first) then order of insertion (oldest first).
2187 * Once we run out of events we loop over each permitted solver in turn
2188 * (easiest first) until either a deduction is made (and an event therefore
2189 * emerges) or no further deductions can be made (in which case we've failed).
2192 * * How do we 'loop over' a solver when both dots and squares are concerned.
2193 * Answer: first all squares then all dots.
2196 static int easy_mode_deductions(solver_state
*sstate
)
2198 int i
, current_yes
, current_no
;
2199 game_state
*state
= sstate
->state
;
2200 grid
*g
= state
->game_grid
;
2201 int diff
= DIFF_MAX
;
2203 /* Per-face deductions */
2204 for (i
= 0; i
< g
->num_faces
; i
++) {
2205 grid_face
*f
= g
->faces
+ i
;
2207 if (sstate
->face_solved
[i
])
2210 current_yes
= sstate
->face_yes_count
[i
];
2211 current_no
= sstate
->face_no_count
[i
];
2213 if (current_yes
+ current_no
== f
->order
) {
2214 sstate
->face_solved
[i
] = TRUE
;
2218 if (state
->clues
[i
] < 0)
2221 if (state
->clues
[i
] < current_yes
) {
2222 sstate
->solver_status
= SOLVER_MISTAKE
;
2225 if (state
->clues
[i
] == current_yes
) {
2226 if (face_setall(sstate
, i
, LINE_UNKNOWN
, LINE_NO
))
2227 diff
= min(diff
, DIFF_EASY
);
2228 sstate
->face_solved
[i
] = TRUE
;
2232 if (f
->order
- state
->clues
[i
] < current_no
) {
2233 sstate
->solver_status
= SOLVER_MISTAKE
;
2236 if (f
->order
- state
->clues
[i
] == current_no
) {
2237 if (face_setall(sstate
, i
, LINE_UNKNOWN
, LINE_YES
))
2238 diff
= min(diff
, DIFF_EASY
);
2239 sstate
->face_solved
[i
] = TRUE
;
2244 check_caches(sstate
);
2246 /* Per-dot deductions */
2247 for (i
= 0; i
< g
->num_dots
; i
++) {
2248 grid_dot
*d
= g
->dots
+ i
;
2249 int yes
, no
, unknown
;
2251 if (sstate
->dot_solved
[i
])
2254 yes
= sstate
->dot_yes_count
[i
];
2255 no
= sstate
->dot_no_count
[i
];
2256 unknown
= d
->order
- yes
- no
;
2260 sstate
->dot_solved
[i
] = TRUE
;
2261 } else if (unknown
== 1) {
2262 dot_setall(sstate
, i
, LINE_UNKNOWN
, LINE_NO
);
2263 diff
= min(diff
, DIFF_EASY
);
2264 sstate
->dot_solved
[i
] = TRUE
;
2266 } else if (yes
== 1) {
2268 sstate
->solver_status
= SOLVER_MISTAKE
;
2270 } else if (unknown
== 1) {
2271 dot_setall(sstate
, i
, LINE_UNKNOWN
, LINE_YES
);
2272 diff
= min(diff
, DIFF_EASY
);
2274 } else if (yes
== 2) {
2276 dot_setall(sstate
, i
, LINE_UNKNOWN
, LINE_NO
);
2277 diff
= min(diff
, DIFF_EASY
);
2279 sstate
->dot_solved
[i
] = TRUE
;
2281 sstate
->solver_status
= SOLVER_MISTAKE
;
2286 check_caches(sstate
);
2291 static int normal_mode_deductions(solver_state
*sstate
)
2293 game_state
*state
= sstate
->state
;
2294 grid
*g
= state
->game_grid
;
2295 char *dlines
= sstate
->normal
->dlines
;
2297 int diff
= DIFF_MAX
;
2299 /* ------ Face deductions ------ */
2301 /* Given a set of dline atmostone/atleastone constraints, need to figure
2302 * out if we can deduce any further info. For more general faces than
2303 * squares, this turns out to be a tricky problem.
2304 * The approach taken here is to define (per face) NxN matrices:
2305 * "maxs" and "mins".
2306 * The entries maxs(j,k) and mins(j,k) define the upper and lower limits
2307 * for the possible number of edges that are YES between positions j and k
2308 * going clockwise around the face. Can think of j and k as marking dots
2309 * around the face (recall the labelling scheme: edge0 joins dot0 to dot1,
2310 * edge1 joins dot1 to dot2 etc).
2311 * Trivially, mins(j,j) = maxs(j,j) = 0, and we don't even bother storing
2312 * these. mins(j,j+1) and maxs(j,j+1) are determined by whether edge{j}
2313 * is YES, NO or UNKNOWN. mins(j,j+2) and maxs(j,j+2) are related to
2314 * the dline atmostone/atleastone status for edges j and j+1.
2316 * Then we calculate the remaining entries recursively. We definitely
2318 * mins(j,k) >= { mins(j,u) + mins(u,k) } for any u between j and k.
2319 * This is because any valid placement of YESs between j and k must give
2320 * a valid placement between j and u, and also between u and k.
2321 * I believe it's sufficient to use just the two values of u:
2322 * j+1 and j+2. Seems to work well in practice - the bounds we compute
2323 * are rigorous, even if they might not be best-possible.
2325 * Once we have maxs and mins calculated, we can make inferences about
2326 * each dline{j,j+1} by looking at the possible complementary edge-counts
2327 * mins(j+2,j) and maxs(j+2,j) and comparing these with the face clue.
2328 * As well as dlines, we can make similar inferences about single edges.
2329 * For example, consider a pentagon with clue 3, and we know at most one
2330 * of (edge0, edge1) is YES, and at most one of (edge2, edge3) is YES.
2331 * We could then deduce edge4 is YES, because maxs(0,4) would be 2, so
2332 * that final edge would have to be YES to make the count up to 3.
2335 /* Much quicker to allocate arrays on the stack than the heap, so
2336 * define the largest possible face size, and base our array allocations
2337 * on that. We check this with an assertion, in case someone decides to
2338 * make a grid which has larger faces than this. Note, this algorithm
2339 * could get quite expensive if there are many large faces. */
2340 #define MAX_FACE_SIZE 8
2342 for (i
= 0; i
< g
->num_faces
; i
++) {
2343 int maxs
[MAX_FACE_SIZE
][MAX_FACE_SIZE
];
2344 int mins
[MAX_FACE_SIZE
][MAX_FACE_SIZE
];
2345 grid_face
*f
= g
->faces
+ i
;
2348 int clue
= state
->clues
[i
];
2349 assert(N
<= MAX_FACE_SIZE
);
2350 if (sstate
->face_solved
[i
])
2352 if (clue
< 0) continue;
2354 /* Calculate the (j,j+1) entries */
2355 for (j
= 0; j
< N
; j
++) {
2356 int edge_index
= f
->edges
[j
] - g
->edges
;
2358 enum line_state line1
= state
->lines
[edge_index
];
2359 enum line_state line2
;
2363 maxs
[j
][k
] = (line1
== LINE_NO
) ?
0 : 1;
2364 mins
[j
][k
] = (line1
== LINE_YES
) ?
1 : 0;
2365 /* Calculate the (j,j+2) entries */
2366 dline_index
= dline_index_from_face(g
, f
, k
);
2367 edge_index
= f
->edges
[k
] - g
->edges
;
2368 line2
= state
->lines
[edge_index
];
2374 if (line1
== LINE_NO
) tmp
--;
2375 if (line2
== LINE_NO
) tmp
--;
2376 if (tmp
== 2 && is_atmostone(dlines
, dline_index
))
2382 if (line1
== LINE_YES
) tmp
++;
2383 if (line2
== LINE_YES
) tmp
++;
2384 if (tmp
== 0 && is_atleastone(dlines
, dline_index
))
2389 /* Calculate the (j,j+m) entries for m between 3 and N-1 */
2390 for (m
= 3; m
< N
; m
++) {
2391 for (j
= 0; j
< N
; j
++) {
2399 maxs
[j
][k
] = maxs
[j
][u
] + maxs
[u
][k
];
2400 mins
[j
][k
] = mins
[j
][u
] + mins
[u
][k
];
2401 tmp
= maxs
[j
][v
] + maxs
[v
][k
];
2402 maxs
[j
][k
] = min(maxs
[j
][k
], tmp
);
2403 tmp
= mins
[j
][v
] + mins
[v
][k
];
2404 mins
[j
][k
] = max(mins
[j
][k
], tmp
);
2408 /* See if we can make any deductions */
2409 for (j
= 0; j
< N
; j
++) {
2411 grid_edge
*e
= f
->edges
[j
];
2412 int line_index
= e
- g
->edges
;
2415 if (state
->lines
[line_index
] != LINE_UNKNOWN
)
2420 /* minimum YESs in the complement of this edge */
2421 if (mins
[k
][j
] > clue
) {
2422 sstate
->solver_status
= SOLVER_MISTAKE
;
2425 if (mins
[k
][j
] == clue
) {
2426 /* setting this edge to YES would make at least
2427 * (clue+1) edges - contradiction */
2428 solver_set_line(sstate
, line_index
, LINE_NO
);
2429 diff
= min(diff
, DIFF_EASY
);
2431 if (maxs
[k
][j
] < clue
- 1) {
2432 sstate
->solver_status
= SOLVER_MISTAKE
;
2435 if (maxs
[k
][j
] == clue
- 1) {
2436 /* Only way to satisfy the clue is to set edge{j} as YES */
2437 solver_set_line(sstate
, line_index
, LINE_YES
);
2438 diff
= min(diff
, DIFF_EASY
);
2441 /* Now see if we can make dline deduction for edges{j,j+1} */
2443 if (state
->lines
[e
- g
->edges
] != LINE_UNKNOWN
)
2444 /* Only worth doing this for an UNKNOWN,UNKNOWN pair.
2445 * Dlines where one of the edges is known, are handled in the
2449 dline_index
= dline_index_from_face(g
, f
, k
);
2453 /* minimum YESs in the complement of this dline */
2454 if (mins
[k
][j
] > clue
- 2) {
2455 /* Adding 2 YESs would break the clue */
2456 if (set_atmostone(dlines
, dline_index
))
2457 diff
= min(diff
, DIFF_NORMAL
);
2459 /* maximum YESs in the complement of this dline */
2460 if (maxs
[k
][j
] < clue
) {
2461 /* Adding 2 NOs would mean not enough YESs */
2462 if (set_atleastone(dlines
, dline_index
))
2463 diff
= min(diff
, DIFF_NORMAL
);
2468 if (diff
< DIFF_NORMAL
)
2471 /* ------ Dot deductions ------ */
2473 for (i
= 0; i
< g
->num_dots
; i
++) {
2474 grid_dot
*d
= g
->dots
+ i
;
2476 int yes
, no
, unknown
;
2478 if (sstate
->dot_solved
[i
])
2480 yes
= sstate
->dot_yes_count
[i
];
2481 no
= sstate
->dot_no_count
[i
];
2482 unknown
= N
- yes
- no
;
2484 for (j
= 0; j
< N
; j
++) {
2487 int line1_index
, line2_index
;
2488 enum line_state line1
, line2
;
2491 dline_index
= dline_index_from_dot(g
, d
, j
);
2492 line1_index
= d
->edges
[j
] - g
->edges
;
2493 line2_index
= d
->edges
[k
] - g
->edges
;
2494 line1
= state
->lines
[line1_index
];
2495 line2
= state
->lines
[line2_index
];
2497 /* Infer dline state from line state */
2498 if (line1
== LINE_NO
|| line2
== LINE_NO
) {
2499 if (set_atmostone(dlines
, dline_index
))
2500 diff
= min(diff
, DIFF_NORMAL
);
2502 if (line1
== LINE_YES
|| line2
== LINE_YES
) {
2503 if (set_atleastone(dlines
, dline_index
))
2504 diff
= min(diff
, DIFF_NORMAL
);
2506 /* Infer line state from dline state */
2507 if (is_atmostone(dlines
, dline_index
)) {
2508 if (line1
== LINE_YES
&& line2
== LINE_UNKNOWN
) {
2509 solver_set_line(sstate
, line2_index
, LINE_NO
);
2510 diff
= min(diff
, DIFF_EASY
);
2512 if (line2
== LINE_YES
&& line1
== LINE_UNKNOWN
) {
2513 solver_set_line(sstate
, line1_index
, LINE_NO
);
2514 diff
= min(diff
, DIFF_EASY
);
2517 if (is_atleastone(dlines
, dline_index
)) {
2518 if (line1
== LINE_NO
&& line2
== LINE_UNKNOWN
) {
2519 solver_set_line(sstate
, line2_index
, LINE_YES
);
2520 diff
= min(diff
, DIFF_EASY
);
2522 if (line2
== LINE_NO
&& line1
== LINE_UNKNOWN
) {
2523 solver_set_line(sstate
, line1_index
, LINE_YES
);
2524 diff
= min(diff
, DIFF_EASY
);
2527 /* Deductions that depend on the numbers of lines.
2528 * Only bother if both lines are UNKNOWN, otherwise the
2529 * easy-mode solver (or deductions above) would have taken
2531 if (line1
!= LINE_UNKNOWN
|| line2
!= LINE_UNKNOWN
)
2534 if (yes
== 0 && unknown
== 2) {
2535 /* Both these unknowns must be identical. If we know
2536 * atmostone or atleastone, we can make progress. */
2537 if (is_atmostone(dlines
, dline_index
)) {
2538 solver_set_line(sstate
, line1_index
, LINE_NO
);
2539 solver_set_line(sstate
, line2_index
, LINE_NO
);
2540 diff
= min(diff
, DIFF_EASY
);
2542 if (is_atleastone(dlines
, dline_index
)) {
2543 solver_set_line(sstate
, line1_index
, LINE_YES
);
2544 solver_set_line(sstate
, line2_index
, LINE_YES
);
2545 diff
= min(diff
, DIFF_EASY
);
2549 if (set_atmostone(dlines
, dline_index
))
2550 diff
= min(diff
, DIFF_NORMAL
);
2552 if (set_atleastone(dlines
, dline_index
))
2553 diff
= min(diff
, DIFF_NORMAL
);
2557 /* If we have atleastone set for this dline, infer
2558 * atmostone for each "opposite" dline (that is, each
2559 * dline without edges in common with this one).
2560 * Again, this test is only worth doing if both these
2561 * lines are UNKNOWN. For if one of these lines were YES,
2562 * the (yes == 1) test above would kick in instead. */
2563 if (is_atleastone(dlines
, dline_index
)) {
2565 for (opp
= 0; opp
< N
; opp
++) {
2566 int opp_dline_index
;
2567 if (opp
== j
|| opp
== j
+1 || opp
== j
-1)
2569 if (j
== 0 && opp
== N
-1)
2571 if (j
== N
-1 && opp
== 0)
2573 opp_dline_index
= dline_index_from_dot(g
, d
, opp
);
2574 if (set_atmostone(dlines
, opp_dline_index
))
2575 diff
= min(diff
, DIFF_NORMAL
);
2578 if (yes
== 0 && is_atmostone(dlines
, dline_index
)) {
2579 /* This dline has *exactly* one YES and there are no
2580 * other YESs. This allows more deductions. */
2582 /* Third unknown must be YES */
2583 for (opp
= 0; opp
< N
; opp
++) {
2585 if (opp
== j
|| opp
== k
)
2587 opp_index
= d
->edges
[opp
] - g
->edges
;
2588 if (state
->lines
[opp_index
] == LINE_UNKNOWN
) {
2589 solver_set_line(sstate
, opp_index
, LINE_YES
);
2590 diff
= min(diff
, DIFF_EASY
);
2593 } else if (unknown
== 4) {
2594 /* Exactly one of opposite UNKNOWNS is YES. We've
2595 * already set atmostone, so set atleastone as well.
2597 if (dline_set_opp_atleastone(sstate
, d
, j
))
2598 diff
= min(diff
, DIFF_NORMAL
);
2607 static int hard_mode_deductions(solver_state
*sstate
)
2609 game_state
*state
= sstate
->state
;
2610 grid
*g
= state
->game_grid
;
2611 char *dlines
= sstate
->normal
->dlines
;
2613 int diff
= DIFF_MAX
;
2616 /* ------ Face deductions ------ */
2618 /* A fully-general linedsf deduction seems overly complicated
2619 * (I suspect the problem is NP-complete, though in practice it might just
2620 * be doable because faces are limited in size).
2621 * For simplicity, we only consider *pairs* of LINE_UNKNOWNS that are
2622 * known to be identical. If setting them both to YES (or NO) would break
2623 * the clue, set them to NO (or YES). */
2625 for (i
= 0; i
< g
->num_faces
; i
++) {
2626 int N
, yes
, no
, unknown
;
2629 if (sstate
->face_solved
[i
])
2631 clue
= state
->clues
[i
];
2635 N
= g
->faces
[i
].order
;
2636 yes
= sstate
->face_yes_count
[i
];
2637 if (yes
+ 1 == clue
) {
2638 if (face_setall_identical(sstate
, i
, LINE_NO
))
2639 diff
= min(diff
, DIFF_EASY
);
2641 no
= sstate
->face_no_count
[i
];
2642 if (no
+ 1 == N
- clue
) {
2643 if (face_setall_identical(sstate
, i
, LINE_YES
))
2644 diff
= min(diff
, DIFF_EASY
);
2647 /* Reload YES count, it might have changed */
2648 yes
= sstate
->face_yes_count
[i
];
2649 unknown
= N
- no
- yes
;
2651 /* Deductions with small number of LINE_UNKNOWNs, based on overall
2652 * parity of lines. */
2653 diff_tmp
= parity_deductions(sstate
, g
->faces
[i
].edges
,
2654 (clue
- yes
) % 2, unknown
);
2655 diff
= min(diff
, diff_tmp
);
2658 /* ------ Dot deductions ------ */
2659 for (i
= 0; i
< g
->num_dots
; i
++) {
2660 grid_dot
*d
= g
->dots
+ i
;
2663 int yes
, no
, unknown
;
2664 /* Go through dlines, and do any dline<->linedsf deductions wherever
2665 * we find two UNKNOWNS. */
2666 for (j
= 0; j
< N
; j
++) {
2667 int dline_index
= dline_index_from_dot(g
, d
, j
);
2670 int can1
, can2
, inv1
, inv2
;
2672 line1_index
= d
->edges
[j
] - g
->edges
;
2673 if (state
->lines
[line1_index
] != LINE_UNKNOWN
)
2676 if (j2
== N
) j2
= 0;
2677 line2_index
= d
->edges
[j2
] - g
->edges
;
2678 if (state
->lines
[line2_index
] != LINE_UNKNOWN
)
2680 /* Infer dline flags from linedsf */
2681 can1
= edsf_canonify(sstate
->hard
->linedsf
, line1_index
, &inv1
);
2682 can2
= edsf_canonify(sstate
->hard
->linedsf
, line2_index
, &inv2
);
2683 if (can1
== can2
&& inv1
!= inv2
) {
2684 /* These are opposites, so set dline atmostone/atleastone */
2685 if (set_atmostone(dlines
, dline_index
))
2686 diff
= min(diff
, DIFF_NORMAL
);
2687 if (set_atleastone(dlines
, dline_index
))
2688 diff
= min(diff
, DIFF_NORMAL
);
2691 /* Infer linedsf from dline flags */
2692 if (is_atmostone(dlines
, dline_index
)
2693 && is_atleastone(dlines
, dline_index
)) {
2694 if (merge_lines(sstate
, line1_index
, line2_index
, 1))
2695 diff
= min(diff
, DIFF_HARD
);
2699 /* Deductions with small number of LINE_UNKNOWNs, based on overall
2700 * parity of lines. */
2701 yes
= sstate
->dot_yes_count
[i
];
2702 no
= sstate
->dot_no_count
[i
];
2703 unknown
= N
- yes
- no
;
2704 diff_tmp
= parity_deductions(sstate
, d
->edges
,
2706 diff
= min(diff
, diff_tmp
);
2709 /* ------ Edge dsf deductions ------ */
2711 /* If the state of a line is known, deduce the state of its canonical line
2712 * too, and vice versa. */
2713 for (i
= 0; i
< g
->num_edges
; i
++) {
2716 can
= edsf_canonify(sstate
->hard
->linedsf
, i
, &inv
);
2719 s
= sstate
->state
->lines
[can
];
2720 if (s
!= LINE_UNKNOWN
) {
2721 if (solver_set_line(sstate
, i
, inv ?
OPP(s
) : s
))
2722 diff
= min(diff
, DIFF_EASY
);
2724 s
= sstate
->state
->lines
[i
];
2725 if (s
!= LINE_UNKNOWN
) {
2726 if (solver_set_line(sstate
, can
, inv ?
OPP(s
) : s
))
2727 diff
= min(diff
, DIFF_EASY
);
2735 static int loop_deductions(solver_state
*sstate
)
2737 int edgecount
= 0, clues
= 0, satclues
= 0, sm1clues
= 0;
2738 game_state
*state
= sstate
->state
;
2739 grid
*g
= state
->game_grid
;
2740 int shortest_chainlen
= g
->num_dots
;
2741 int loop_found
= FALSE
;
2743 int progress
= FALSE
;
2747 * Go through the grid and update for all the new edges.
2748 * Since merge_dots() is idempotent, the simplest way to
2749 * do this is just to update for _all_ the edges.
2750 * Also, while we're here, we count the edges.
2752 for (i
= 0; i
< g
->num_edges
; i
++) {
2753 if (state
->lines
[i
] == LINE_YES
) {
2754 loop_found
|= merge_dots(sstate
, i
);
2760 * Count the clues, count the satisfied clues, and count the
2761 * satisfied-minus-one clues.
2763 for (i
= 0; i
< g
->num_faces
; i
++) {
2764 int c
= state
->clues
[i
];
2766 int o
= sstate
->face_yes_count
[i
];
2775 for (i
= 0; i
< g
->num_dots
; ++i
) {
2777 sstate
->looplen
[dsf_canonify(sstate
->dotdsf
, i
)];
2778 if (dots_connected
> 1)
2779 shortest_chainlen
= min(shortest_chainlen
, dots_connected
);
2782 assert(sstate
->solver_status
== SOLVER_INCOMPLETE
);
2784 if (satclues
== clues
&& shortest_chainlen
== edgecount
) {
2785 sstate
->solver_status
= SOLVER_SOLVED
;
2786 /* This discovery clearly counts as progress, even if we haven't
2787 * just added any lines or anything */
2789 goto finished_loop_deductionsing
;
2793 * Now go through looking for LINE_UNKNOWN edges which
2794 * connect two dots that are already in the same
2795 * equivalence class. If we find one, test to see if the
2796 * loop it would create is a solution.
2798 for (i
= 0; i
< g
->num_edges
; i
++) {
2799 grid_edge
*e
= g
->edges
+ i
;
2800 int d1
= e
->dot1
- g
->dots
;
2801 int d2
= e
->dot2
- g
->dots
;
2803 if (state
->lines
[i
] != LINE_UNKNOWN
)
2806 eqclass
= dsf_canonify(sstate
->dotdsf
, d1
);
2807 if (eqclass
!= dsf_canonify(sstate
->dotdsf
, d2
))
2810 val
= LINE_NO
; /* loop is bad until proven otherwise */
2813 * This edge would form a loop. Next
2814 * question: how long would the loop be?
2815 * Would it equal the total number of edges
2816 * (plus the one we'd be adding if we added
2819 if (sstate
->looplen
[eqclass
] == edgecount
+ 1) {
2823 * This edge would form a loop which
2824 * took in all the edges in the entire
2825 * grid. So now we need to work out
2826 * whether it would be a valid solution
2827 * to the puzzle, which means we have to
2828 * check if it satisfies all the clues.
2829 * This means that every clue must be
2830 * either satisfied or satisfied-minus-
2831 * 1, and also that the number of
2832 * satisfied-minus-1 clues must be at
2833 * most two and they must lie on either
2834 * side of this edge.
2838 int f
= e
->face1
- g
->faces
;
2839 int c
= state
->clues
[f
];
2840 if (c
>= 0 && sstate
->face_yes_count
[f
] == c
- 1)
2844 int f
= e
->face2
- g
->faces
;
2845 int c
= state
->clues
[f
];
2846 if (c
>= 0 && sstate
->face_yes_count
[f
] == c
- 1)
2849 if (sm1clues
== sm1_nearby
&&
2850 sm1clues
+ satclues
== clues
) {
2851 val
= LINE_YES
; /* loop is good! */
2856 * Right. Now we know that adding this edge
2857 * would form a loop, and we know whether
2858 * that loop would be a viable solution or
2861 * If adding this edge produces a solution,
2862 * then we know we've found _a_ solution but
2863 * we don't know that it's _the_ solution -
2864 * if it were provably the solution then
2865 * we'd have deduced this edge some time ago
2866 * without the need to do loop detection. So
2867 * in this state we return SOLVER_AMBIGUOUS,
2868 * which has the effect that hitting Solve
2869 * on a user-provided puzzle will fill in a
2870 * solution but using the solver to
2871 * construct new puzzles won't consider this
2872 * a reasonable deduction for the user to
2875 progress
= solver_set_line(sstate
, i
, val
);
2876 assert(progress
== TRUE
);
2877 if (val
== LINE_YES
) {
2878 sstate
->solver_status
= SOLVER_AMBIGUOUS
;
2879 goto finished_loop_deductionsing
;
2883 finished_loop_deductionsing
:
2884 return progress ? DIFF_EASY
: DIFF_MAX
;
2887 /* This will return a dynamically allocated solver_state containing the (more)
2889 static solver_state
*solve_game_rec(const solver_state
*sstate_start
,
2892 solver_state
*sstate
, *sstate_saved
;
2893 int solver_progress
;
2896 /* Indicates which solver we should call next. This is a sensible starting
2898 int current_solver
= DIFF_EASY
, next_solver
;
2899 sstate
= dup_solver_state(sstate_start
);
2901 /* Cache the values of some variables for readability */
2902 state
= sstate
->state
;
2904 sstate_saved
= NULL
;
2906 solver_progress
= FALSE
;
2908 check_caches(sstate
);
2911 if (sstate
->solver_status
== SOLVER_MISTAKE
)
2914 next_solver
= solver_fns
[current_solver
](sstate
);
2916 if (next_solver
== DIFF_MAX
) {
2917 if (current_solver
< diff
&& current_solver
+ 1 < DIFF_MAX
) {
2918 /* Try next beefier solver */
2919 next_solver
= current_solver
+ 1;
2921 next_solver
= loop_deductions(sstate
);
2925 if (sstate
->solver_status
== SOLVER_SOLVED
||
2926 sstate
->solver_status
== SOLVER_AMBIGUOUS
) {
2927 /* fprintf(stderr, "Solver completed\n"); */
2931 /* Once we've looped over all permitted solvers then the loop
2932 * deductions without making any progress, we'll exit this while loop */
2933 current_solver
= next_solver
;
2934 } while (current_solver
< DIFF_MAX
);
2936 if (sstate
->solver_status
== SOLVER_SOLVED
||
2937 sstate
->solver_status
== SOLVER_AMBIGUOUS
) {
2938 /* s/LINE_UNKNOWN/LINE_NO/g */
2939 array_setall(sstate
->state
->lines
, LINE_UNKNOWN
, LINE_NO
,
2940 sstate
->state
->game_grid
->num_edges
);
2947 static char *solve_game(game_state
*state
, game_state
*currstate
,
2948 char *aux
, char **error
)
2951 solver_state
*sstate
, *new_sstate
;
2953 sstate
= new_solver_state(state
, DIFF_MAX
);
2954 new_sstate
= solve_game_rec(sstate
, DIFF_MAX
);
2956 if (new_sstate
->solver_status
== SOLVER_SOLVED
) {
2957 soln
= encode_solve_move(new_sstate
->state
);
2958 } else if (new_sstate
->solver_status
== SOLVER_AMBIGUOUS
) {
2959 soln
= encode_solve_move(new_sstate
->state
);
2960 /**error = "Solver found ambiguous solutions"; */
2962 soln
= encode_solve_move(new_sstate
->state
);
2963 /**error = "Solver failed"; */
2966 free_solver_state(new_sstate
);
2967 free_solver_state(sstate
);
2972 /* ----------------------------------------------------------------------
2973 * Drawing and mouse-handling
2976 static char *interpret_move(game_state
*state
, game_ui
*ui
, game_drawstate
*ds
,
2977 int x
, int y
, int button
)
2979 grid
*g
= state
->game_grid
;
2983 char button_char
= ' ';
2984 enum line_state old_state
;
2986 button
&= ~MOD_MASK
;
2988 /* Convert mouse-click (x,y) to grid coordinates */
2989 x
-= BORDER(ds
->tilesize
);
2990 y
-= BORDER(ds
->tilesize
);
2991 x
= x
* g
->tilesize
/ ds
->tilesize
;
2992 y
= y
* g
->tilesize
/ ds
->tilesize
;
2996 e
= grid_nearest_edge(g
, x
, y
);
3002 /* I think it's only possible to play this game with mouse clicks, sorry */
3003 /* Maybe will add mouse drag support some time */
3004 old_state
= state
->lines
[i
];
3008 switch (old_state
) {
3022 switch (old_state
) {
3037 sprintf(buf
, "%d%c", i
, (int)button_char
);
3043 static game_state
*execute_move(game_state
*state
, char *move
)
3046 game_state
*newstate
= dup_game(state
);
3048 if (move
[0] == 'S') {
3050 newstate
->cheated
= TRUE
;
3055 move
+= strspn(move
, "1234567890");
3056 switch (*(move
++)) {
3058 newstate
->lines
[i
] = LINE_YES
;
3061 newstate
->lines
[i
] = LINE_NO
;
3064 newstate
->lines
[i
] = LINE_UNKNOWN
;
3072 * Check for completion.
3074 if (check_completion(newstate
))
3075 newstate
->solved
= TRUE
;
3080 free_game(newstate
);
3084 /* ----------------------------------------------------------------------
3088 /* Convert from grid coordinates to screen coordinates */
3089 static void grid_to_screen(const game_drawstate
*ds
, const grid
*g
,
3090 int grid_x
, int grid_y
, int *x
, int *y
)
3092 *x
= grid_x
- g
->lowest_x
;
3093 *y
= grid_y
- g
->lowest_y
;
3094 *x
= *x
* ds
->tilesize
/ g
->tilesize
;
3095 *y
= *y
* ds
->tilesize
/ g
->tilesize
;
3096 *x
+= BORDER(ds
->tilesize
);
3097 *y
+= BORDER(ds
->tilesize
);
3100 /* Returns (into x,y) position of centre of face for rendering the text clue.
3102 static void face_text_pos(const game_drawstate
*ds
, const grid
*g
,
3103 const grid_face
*f
, int *x
, int *y
)
3107 /* Simplest solution is the centroid. Might not work in some cases. */
3109 /* Another algorithm to look into:
3110 * Find the midpoints of the sides, find the bounding-box,
3111 * then take the centre of that. */
3113 /* Best solution probably involves incentres (inscribed circles) */
3115 int sx
= 0, sy
= 0; /* sums */
3116 for (i
= 0; i
< f
->order
; i
++) {
3117 grid_dot
*d
= f
->dots
[i
];
3124 /* convert to screen coordinates */
3125 grid_to_screen(ds
, g
, sx
, sy
, x
, y
);
3128 static void game_redraw(drawing
*dr
, game_drawstate
*ds
, game_state
*oldstate
,
3129 game_state
*state
, int dir
, game_ui
*ui
,
3130 float animtime
, float flashtime
)
3132 grid
*g
= state
->game_grid
;
3133 int border
= BORDER(ds
->tilesize
);
3136 int line_colour
, flash_changed
;
3142 * The initial contents of the window are not guaranteed and
3143 * can vary with front ends. To be on the safe side, all games
3144 * should start by drawing a big background-colour rectangle
3145 * covering the whole window.
3147 int grid_width
= g
->highest_x
- g
->lowest_x
;
3148 int grid_height
= g
->highest_y
- g
->lowest_y
;
3149 int w
= grid_width
* ds
->tilesize
/ g
->tilesize
;
3150 int h
= grid_height
* ds
->tilesize
/ g
->tilesize
;
3151 draw_rect(dr
, 0, 0, w
+ 2 * border
+ 1, h
+ 2 * border
+ 1,
3155 for (i
= 0; i
< g
->num_faces
; i
++) {
3159 c
[0] = CLUE2CHAR(state
->clues
[i
]);
3162 face_text_pos(ds
, g
, f
, &x
, &y
);
3163 draw_text(dr
, x
, y
, FONT_VARIABLE
, ds
->tilesize
/2,
3164 ALIGN_VCENTRE
| ALIGN_HCENTRE
, COL_FOREGROUND
, c
);
3166 draw_update(dr
, 0, 0, w
+ 2 * border
, h
+ 2 * border
);
3169 if (flashtime
> 0 &&
3170 (flashtime
<= FLASH_TIME
/3 ||
3171 flashtime
>= FLASH_TIME
*2/3)) {
3172 flash_changed
= !ds
->flashing
;
3173 ds
->flashing
= TRUE
;
3175 flash_changed
= ds
->flashing
;
3176 ds
->flashing
= FALSE
;
3179 /* Some platforms may perform anti-aliasing, which may prevent clean
3180 * repainting of lines when the colour is changed.
3181 * If a line needs to be over-drawn in a different colour, erase a
3182 * bounding-box around the line, then flag all nearby objects for redraw.
3185 const char redraw_flag
= (char)(1<<7);
3186 for (i
= 0; i
< g
->num_edges
; i
++) {
3187 char prev_ds
= (ds
->lines
[i
] & ~redraw_flag
);
3188 char new_ds
= state
->lines
[i
];
3189 if (state
->line_errors
[i
])
3190 new_ds
= DS_LINE_ERROR
;
3192 /* If we're changing state, AND
3193 * the previous state was a coloured line */
3194 if ((prev_ds
!= new_ds
) && (prev_ds
!= LINE_NO
)) {
3195 grid_edge
*e
= g
->edges
+ i
;
3196 int x1
= e
->dot1
->x
;
3197 int y1
= e
->dot1
->y
;
3198 int x2
= e
->dot2
->x
;
3199 int y2
= e
->dot2
->y
;
3200 int xmin
, xmax
, ymin
, ymax
;
3202 grid_to_screen(ds
, g
, x1
, y1
, &x1
, &y1
);
3203 grid_to_screen(ds
, g
, x2
, y2
, &x2
, &y2
);
3204 /* Allow extra margin for dots, and thickness of lines */
3205 xmin
= min(x1
, x2
) - 2;
3206 xmax
= max(x1
, x2
) + 2;
3207 ymin
= min(y1
, y2
) - 2;
3208 ymax
= max(y1
, y2
) + 2;
3209 /* For testing, I find it helpful to change COL_BACKGROUND
3210 * to COL_SATISFIED here. */
3211 draw_rect(dr
, xmin
, ymin
, xmax
- xmin
+ 1, ymax
- ymin
+ 1,
3213 draw_update(dr
, xmin
, ymin
, xmax
- xmin
+ 1, ymax
- ymin
+ 1);
3215 /* Mark nearby lines for redraw */
3216 for (j
= 0; j
< e
->dot1
->order
; j
++)
3217 ds
->lines
[e
->dot1
->edges
[j
] - g
->edges
] |= redraw_flag
;
3218 for (j
= 0; j
< e
->dot2
->order
; j
++)
3219 ds
->lines
[e
->dot2
->edges
[j
] - g
->edges
] |= redraw_flag
;
3220 /* Mark nearby clues for redraw. Use a value that is
3221 * neither TRUE nor FALSE for this. */
3223 ds
->clue_error
[e
->face1
- g
->faces
] = 2;
3225 ds
->clue_error
[e
->face2
- g
->faces
] = 2;
3230 /* Redraw clue colours if necessary */
3231 for (i
= 0; i
< g
->num_faces
; i
++) {
3232 grid_face
*f
= g
->faces
+ i
;
3233 int sides
= f
->order
;
3235 n
= state
->clues
[i
];
3239 c
[0] = CLUE2CHAR(n
);
3242 clue_mistake
= (face_order(state
, i
, LINE_YES
) > n
||
3243 face_order(state
, i
, LINE_NO
) > (sides
-n
));
3245 clue_satisfied
= (face_order(state
, i
, LINE_YES
) == n
&&
3246 face_order(state
, i
, LINE_NO
) == (sides
-n
));
3248 if (clue_mistake
!= ds
->clue_error
[i
]
3249 || clue_satisfied
!= ds
->clue_satisfied
[i
]) {
3251 face_text_pos(ds
, g
, f
, &x
, &y
);
3252 /* There seems to be a certain amount of trial-and-error
3253 * involved in working out the correct bounding-box for
3255 draw_rect(dr
, x
- ds
->tilesize
/4 - 1, y
- ds
->tilesize
/4 - 3,
3256 ds
->tilesize
/2 + 2, ds
->tilesize
/2 + 5,
3259 FONT_VARIABLE
, ds
->tilesize
/2,
3260 ALIGN_VCENTRE
| ALIGN_HCENTRE
,
3261 clue_mistake ? COL_MISTAKE
:
3262 clue_satisfied ? COL_SATISFIED
: COL_FOREGROUND
, c
);
3263 draw_update(dr
, x
- ds
->tilesize
/4 - 1, y
- ds
->tilesize
/4 - 3,
3264 ds
->tilesize
/2 + 2, ds
->tilesize
/2 + 5);
3266 ds
->clue_error
[i
] = clue_mistake
;
3267 ds
->clue_satisfied
[i
] = clue_satisfied
;
3269 /* Sometimes, the bounding-box encroaches into the surrounding
3270 * lines (particularly if the window is resized fairly small).
3271 * So redraw them. */
3272 for (j
= 0; j
< f
->order
; j
++)
3273 ds
->lines
[f
->edges
[j
] - g
->edges
] = -1;
3278 for (i
= 0; i
< g
->num_edges
; i
++) {
3279 grid_edge
*e
= g
->edges
+ i
;
3281 int xmin
, ymin
, xmax
, ymax
;
3282 char new_ds
, need_draw
;
3283 new_ds
= state
->lines
[i
];
3284 if (state
->line_errors
[i
])
3285 new_ds
= DS_LINE_ERROR
;
3286 need_draw
= (new_ds
!= ds
->lines
[i
]) ? TRUE
: FALSE
;
3287 if (flash_changed
&& (state
->lines
[i
] == LINE_YES
))
3290 need_draw
= TRUE
; /* draw everything at the start */
3291 ds
->lines
[i
] = new_ds
;
3294 if (state
->line_errors
[i
])
3295 line_colour
= COL_MISTAKE
;
3296 else if (state
->lines
[i
] == LINE_UNKNOWN
)
3297 line_colour
= COL_LINEUNKNOWN
;
3298 else if (state
->lines
[i
] == LINE_NO
)
3299 line_colour
= COL_BACKGROUND
;
3300 else if (ds
->flashing
)
3301 line_colour
= COL_HIGHLIGHT
;
3303 line_colour
= COL_FOREGROUND
;
3305 /* Convert from grid to screen coordinates */
3306 grid_to_screen(ds
, g
, e
->dot1
->x
, e
->dot1
->y
, &x1
, &y1
);
3307 grid_to_screen(ds
, g
, e
->dot2
->x
, e
->dot2
->y
, &x2
, &y2
);
3314 if (line_colour
!= COL_BACKGROUND
) {
3315 /* (dx, dy) points roughly from (x1, y1) to (x2, y2).
3316 * The line is then "fattened" in a (roughly) perpendicular
3317 * direction to create a thin rectangle. */
3318 int dx
= (x1
> x2
) ?
-1 : ((x1
< x2
) ?
1 : 0);
3319 int dy
= (y1
> y2
) ?
-1 : ((y1
< y2
) ?
1 : 0);
3321 points
[0] = x1
+ dy
;
3322 points
[1] = y1
- dx
;
3323 points
[2] = x1
- dy
;
3324 points
[3] = y1
+ dx
;
3325 points
[4] = x2
- dy
;
3326 points
[5] = y2
+ dx
;
3327 points
[6] = x2
+ dy
;
3328 points
[7] = y2
- dx
;
3329 draw_polygon(dr
, points
, 4, line_colour
, line_colour
);
3332 /* Draw dots at ends of the line */
3333 draw_circle(dr
, x1
, y1
, 2, COL_FOREGROUND
, COL_FOREGROUND
);
3334 draw_circle(dr
, x2
, y2
, 2, COL_FOREGROUND
, COL_FOREGROUND
);
3336 draw_update(dr
, xmin
-2, ymin
-2, xmax
- xmin
+ 4, ymax
- ymin
+ 4);
3341 for (i
= 0; i
< g
->num_dots
; i
++) {
3342 grid_dot
*d
= g
->dots
+ i
;
3344 grid_to_screen(ds
, g
, d
->x
, d
->y
, &x
, &y
);
3345 draw_circle(dr
, x
, y
, 2, COL_FOREGROUND
, COL_FOREGROUND
);
3351 static float game_flash_length(game_state
*oldstate
, game_state
*newstate
,
3352 int dir
, game_ui
*ui
)
3354 if (!oldstate
->solved
&& newstate
->solved
&&
3355 !oldstate
->cheated
&& !newstate
->cheated
) {
3362 static void game_print_size(game_params
*params
, float *x
, float *y
)
3367 * I'll use 7mm "squares" by default.
3369 game_compute_size(params
, 700, &pw
, &ph
);
3374 static void game_print(drawing
*dr
, game_state
*state
, int tilesize
)
3376 int ink
= print_mono_colour(dr
, 0);
3378 game_drawstate ads
, *ds
= &ads
;
3379 grid
*g
= state
->game_grid
;
3381 game_set_size(dr
, ds
, NULL
, tilesize
);
3383 for (i
= 0; i
< g
->num_dots
; i
++) {
3385 grid_to_screen(ds
, g
, g
->dots
[i
].x
, g
->dots
[i
].y
, &x
, &y
);
3386 draw_circle(dr
, x
, y
, ds
->tilesize
/ 15, ink
, ink
);
3392 for (i
= 0; i
< g
->num_faces
; i
++) {
3393 grid_face
*f
= g
->faces
+ i
;
3394 int clue
= state
->clues
[i
];
3398 c
[0] = CLUE2CHAR(clue
);
3400 face_text_pos(ds
, g
, f
, &x
, &y
);
3402 FONT_VARIABLE
, ds
->tilesize
/ 2,
3403 ALIGN_VCENTRE
| ALIGN_HCENTRE
, ink
, c
);
3410 for (i
= 0; i
< g
->num_edges
; i
++) {
3411 int thickness
= (state
->lines
[i
] == LINE_YES
) ?
30 : 150;
3412 grid_edge
*e
= g
->edges
+ i
;
3414 grid_to_screen(ds
, g
, e
->dot1
->x
, e
->dot1
->y
, &x1
, &y1
);
3415 grid_to_screen(ds
, g
, e
->dot2
->x
, e
->dot2
->y
, &x2
, &y2
);
3416 if (state
->lines
[i
] == LINE_YES
)
3418 /* (dx, dy) points from (x1, y1) to (x2, y2).
3419 * The line is then "fattened" in a perpendicular
3420 * direction to create a thin rectangle. */
3421 double d
= sqrt(SQ((double)x1
- x2
) + SQ((double)y1
- y2
));
3422 double dx
= (x2
- x1
) / d
;
3423 double dy
= (y2
- y1
) / d
;
3426 dx
= (dx
* ds
->tilesize
) / thickness
;
3427 dy
= (dy
* ds
->tilesize
) / thickness
;
3428 points
[0] = x1
+ (int)dy
;
3429 points
[1] = y1
- (int)dx
;
3430 points
[2] = x1
- (int)dy
;
3431 points
[3] = y1
+ (int)dx
;
3432 points
[4] = x2
- (int)dy
;
3433 points
[5] = y2
+ (int)dx
;
3434 points
[6] = x2
+ (int)dy
;
3435 points
[7] = y2
- (int)dx
;
3436 draw_polygon(dr
, points
, 4, ink
, ink
);
3440 /* Draw a dotted line */
3443 for (j
= 1; j
< divisions
; j
++) {
3444 /* Weighted average */
3445 int x
= (x1
* (divisions
-j
) + x2
* j
) / divisions
;
3446 int y
= (y1
* (divisions
-j
) + y2
* j
) / divisions
;
3447 draw_circle(dr
, x
, y
, ds
->tilesize
/ thickness
, ink
, ink
);
3454 #define thegame loopy
3457 const struct game thegame
= {
3458 "Loopy", "games.loopy", "loopy",
3465 TRUE
, game_configure
, custom_params
,
3473 TRUE
, game_can_format_as_text_now
, game_text_format
,
3481 PREFERRED_TILE_SIZE
, game_compute_size
, game_set_size
,
3484 game_free_drawstate
,
3488 TRUE
, FALSE
, game_print_size
, game_print
,
3489 FALSE
/* wants_statusbar */,
3490 FALSE
, game_timing_state
,
3491 0, /* mouse_priorities */