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 */
120 /* Used in game_text_format(), so that it knows what type of
121 * grid it's trying to render as ASCII text. */
126 SOLVER_SOLVED
, /* This is the only solution the solver could find */
127 SOLVER_MISTAKE
, /* This is definitely not a solution */
128 SOLVER_AMBIGUOUS
, /* This _might_ be an ambiguous solution */
129 SOLVER_INCOMPLETE
/* This may be a partial solution */
132 /* ------ Solver state ------ */
133 typedef struct normal
{
134 /* For each dline, store a bitmask for whether we know:
135 * (bit 0) at least one is YES
136 * (bit 1) at most one is YES */
140 typedef struct hard
{
144 typedef struct solver_state
{
146 enum solver_status solver_status
;
147 /* NB looplen is the number of dots that are joined together at a point, ie a
148 * looplen of 1 means there are no lines to a particular dot */
154 char *face_yes_count
;
156 char *dot_solved
, *face_solved
;
159 normal_mode_state
*normal
;
160 hard_mode_state
*hard
;
164 * Difficulty levels. I do some macro ickery here to ensure that my
165 * enum and the various forms of my name list always match up.
168 #define DIFFLIST(A) \
169 A(EASY,Easy,e,easy_mode_deductions) \
170 A(NORMAL,Normal,n,normal_mode_deductions) \
171 A(HARD,Hard,h,hard_mode_deductions)
172 #define ENUM(upper,title,lower,fn) DIFF_ ## upper,
173 #define TITLE(upper,title,lower,fn) #title,
174 #define ENCODE(upper,title,lower,fn) #lower
175 #define CONFIG(upper,title,lower,fn) ":" #title
176 #define SOLVER_FN_DECL(upper,title,lower,fn) static int fn(solver_state *);
177 #define SOLVER_FN(upper,title,lower,fn) &fn,
178 enum { DIFFLIST(ENUM
) DIFF_MAX
};
179 static char const *const diffnames
[] = { DIFFLIST(TITLE
) };
180 static char const diffchars
[] = DIFFLIST(ENCODE
);
181 #define DIFFCONFIG DIFFLIST(CONFIG)
182 DIFFLIST(SOLVER_FN_DECL
)
183 static int (*(solver_fns
[]))(solver_state
*) = { DIFFLIST(SOLVER_FN
) };
190 /* Grid generation is expensive, so keep a (ref-counted) reference to the
191 * grid for these parameters, and only generate when required. */
195 enum line_state
{ LINE_YES
, LINE_UNKNOWN
, LINE_NO
};
197 #define OPP(line_state) \
201 struct game_drawstate
{
207 char *clue_satisfied
;
210 static char *validate_desc(game_params
*params
, char *desc
);
211 static int dot_order(const game_state
* state
, int i
, char line_type
);
212 static int face_order(const game_state
* state
, int i
, char line_type
);
213 static solver_state
*solve_game_rec(const solver_state
*sstate
,
217 static void check_caches(const solver_state
* sstate
);
219 #define check_caches(s)
222 /* ------- List of grid generators ------- */
223 #define GRIDLIST(A) \
224 A(Squares,grid_new_square) \
225 A(Triangular,grid_new_triangular) \
226 A(Honeycomb,grid_new_honeycomb) \
227 A(Snub-Square,grid_new_snubsquare) \
228 A(Cairo,grid_new_cairo) \
229 A(Great-Hexagonal,grid_new_greathexagonal) \
230 A(Octagonal,grid_new_octagonal) \
231 A(Kites,grid_new_kites)
233 #define GRID_NAME(title,fn) #title,
234 #define GRID_CONFIG(title,fn) ":" #title
235 #define GRID_FN(title,fn) &fn,
236 static char const *const gridnames
[] = { GRIDLIST(GRID_NAME
) };
237 #define GRID_CONFIGS GRIDLIST(GRID_CONFIG)
238 static grid
* (*(grid_fns
[]))(int w
, int h
) = { GRIDLIST(GRID_FN
) };
239 #define NUM_GRID_TYPES (sizeof(grid_fns) / sizeof(grid_fns[0]))
241 /* Generates a (dynamically allocated) new grid, according to the
242 * type and size requested in params. Does nothing if the grid is already
243 * generated. The allocated grid is owned by the params object, and will be
244 * freed in free_params(). */
245 static void params_generate_grid(game_params
*params
)
247 if (!params
->game_grid
) {
248 params
->game_grid
= grid_fns
[params
->type
](params
->w
, params
->h
);
252 /* ----------------------------------------------------------------------
256 /* General constants */
257 #define PREFERRED_TILE_SIZE 32
258 #define BORDER(tilesize) ((tilesize) / 2)
259 #define FLASH_TIME 0.5F
261 #define BIT_SET(field, bit) ((field) & (1<<(bit)))
263 #define SET_BIT(field, bit) (BIT_SET(field, bit) ? FALSE : \
264 ((field) |= (1<<(bit)), TRUE))
266 #define CLEAR_BIT(field, bit) (BIT_SET(field, bit) ? \
267 ((field) &= ~(1<<(bit)), TRUE) : FALSE)
269 #define CLUE2CHAR(c) \
270 ((c < 0) ? ' ' : c + '0')
272 /* ----------------------------------------------------------------------
273 * General struct manipulation and other straightforward code
276 static game_state
*dup_game(game_state
*state
)
278 game_state
*ret
= snew(game_state
);
280 ret
->game_grid
= state
->game_grid
;
281 ret
->game_grid
->refcount
++;
283 ret
->solved
= state
->solved
;
284 ret
->cheated
= state
->cheated
;
286 ret
->clues
= snewn(state
->game_grid
->num_faces
, signed char);
287 memcpy(ret
->clues
, state
->clues
, state
->game_grid
->num_faces
);
289 ret
->lines
= snewn(state
->game_grid
->num_edges
, char);
290 memcpy(ret
->lines
, state
->lines
, state
->game_grid
->num_edges
);
292 ret
->grid_type
= state
->grid_type
;
296 static void free_game(game_state
*state
)
299 grid_free(state
->game_grid
);
306 static solver_state
*new_solver_state(game_state
*state
, int diff
) {
308 int num_dots
= state
->game_grid
->num_dots
;
309 int num_faces
= state
->game_grid
->num_faces
;
310 int num_edges
= state
->game_grid
->num_edges
;
311 solver_state
*ret
= snew(solver_state
);
313 ret
->state
= dup_game(state
);
315 ret
->solver_status
= SOLVER_INCOMPLETE
;
317 ret
->dotdsf
= snew_dsf(num_dots
);
318 ret
->looplen
= snewn(num_dots
, int);
320 for (i
= 0; i
< num_dots
; i
++) {
324 ret
->dot_solved
= snewn(num_dots
, char);
325 ret
->face_solved
= snewn(num_faces
, char);
326 memset(ret
->dot_solved
, FALSE
, num_dots
);
327 memset(ret
->face_solved
, FALSE
, num_faces
);
329 ret
->dot_yes_count
= snewn(num_dots
, char);
330 memset(ret
->dot_yes_count
, 0, num_dots
);
331 ret
->dot_no_count
= snewn(num_dots
, char);
332 memset(ret
->dot_no_count
, 0, num_dots
);
333 ret
->face_yes_count
= snewn(num_faces
, char);
334 memset(ret
->face_yes_count
, 0, num_faces
);
335 ret
->face_no_count
= snewn(num_faces
, char);
336 memset(ret
->face_no_count
, 0, num_faces
);
338 if (diff
< DIFF_NORMAL
) {
341 ret
->normal
= snew(normal_mode_state
);
342 ret
->normal
->dlines
= snewn(2*num_edges
, char);
343 memset(ret
->normal
->dlines
, 0, 2*num_edges
);
346 if (diff
< DIFF_HARD
) {
349 ret
->hard
= snew(hard_mode_state
);
350 ret
->hard
->linedsf
= snew_dsf(state
->game_grid
->num_edges
);
356 static void free_solver_state(solver_state
*sstate
) {
358 free_game(sstate
->state
);
359 sfree(sstate
->dotdsf
);
360 sfree(sstate
->looplen
);
361 sfree(sstate
->dot_solved
);
362 sfree(sstate
->face_solved
);
363 sfree(sstate
->dot_yes_count
);
364 sfree(sstate
->dot_no_count
);
365 sfree(sstate
->face_yes_count
);
366 sfree(sstate
->face_no_count
);
368 if (sstate
->normal
) {
369 sfree(sstate
->normal
->dlines
);
370 sfree(sstate
->normal
);
374 sfree(sstate
->hard
->linedsf
);
382 static solver_state
*dup_solver_state(const solver_state
*sstate
) {
383 game_state
*state
= sstate
->state
;
384 int num_dots
= state
->game_grid
->num_dots
;
385 int num_faces
= state
->game_grid
->num_faces
;
386 int num_edges
= state
->game_grid
->num_edges
;
387 solver_state
*ret
= snew(solver_state
);
389 ret
->state
= state
= dup_game(sstate
->state
);
391 ret
->solver_status
= sstate
->solver_status
;
393 ret
->dotdsf
= snewn(num_dots
, int);
394 ret
->looplen
= snewn(num_dots
, int);
395 memcpy(ret
->dotdsf
, sstate
->dotdsf
,
396 num_dots
* sizeof(int));
397 memcpy(ret
->looplen
, sstate
->looplen
,
398 num_dots
* sizeof(int));
400 ret
->dot_solved
= snewn(num_dots
, char);
401 ret
->face_solved
= snewn(num_faces
, char);
402 memcpy(ret
->dot_solved
, sstate
->dot_solved
, num_dots
);
403 memcpy(ret
->face_solved
, sstate
->face_solved
, num_faces
);
405 ret
->dot_yes_count
= snewn(num_dots
, char);
406 memcpy(ret
->dot_yes_count
, sstate
->dot_yes_count
, num_dots
);
407 ret
->dot_no_count
= snewn(num_dots
, char);
408 memcpy(ret
->dot_no_count
, sstate
->dot_no_count
, num_dots
);
410 ret
->face_yes_count
= snewn(num_faces
, char);
411 memcpy(ret
->face_yes_count
, sstate
->face_yes_count
, num_faces
);
412 ret
->face_no_count
= snewn(num_faces
, char);
413 memcpy(ret
->face_no_count
, sstate
->face_no_count
, num_faces
);
415 if (sstate
->normal
) {
416 ret
->normal
= snew(normal_mode_state
);
417 ret
->normal
->dlines
= snewn(2*num_edges
, char);
418 memcpy(ret
->normal
->dlines
, sstate
->normal
->dlines
,
425 ret
->hard
= snew(hard_mode_state
);
426 ret
->hard
->linedsf
= snewn(num_edges
, int);
427 memcpy(ret
->hard
->linedsf
, sstate
->hard
->linedsf
,
428 num_edges
* sizeof(int));
436 static game_params
*default_params(void)
438 game_params
*ret
= snew(game_params
);
447 ret
->diff
= DIFF_EASY
;
450 ret
->game_grid
= NULL
;
455 static game_params
*dup_params(game_params
*params
)
457 game_params
*ret
= snew(game_params
);
459 *ret
= *params
; /* structure copy */
460 if (ret
->game_grid
) {
461 ret
->game_grid
->refcount
++;
466 static const game_params presets
[] = {
468 { 7, 7, DIFF_EASY
, 0, NULL
},
469 { 7, 7, DIFF_NORMAL
, 0, NULL
},
470 { 7, 7, DIFF_HARD
, 0, NULL
},
471 { 7, 7, DIFF_HARD
, 1, NULL
},
472 { 7, 7, DIFF_HARD
, 2, NULL
},
473 { 5, 5, DIFF_HARD
, 3, NULL
},
474 { 7, 7, DIFF_HARD
, 4, NULL
},
475 { 5, 4, DIFF_HARD
, 5, NULL
},
476 { 5, 5, DIFF_HARD
, 6, NULL
},
477 { 5, 5, DIFF_HARD
, 7, NULL
},
479 { 7, 7, DIFF_EASY
, 0, NULL
},
480 { 10, 10, DIFF_EASY
, 0, NULL
},
481 { 7, 7, DIFF_NORMAL
, 0, NULL
},
482 { 10, 10, DIFF_NORMAL
, 0, NULL
},
483 { 7, 7, DIFF_HARD
, 0, NULL
},
484 { 10, 10, DIFF_HARD
, 0, NULL
},
485 { 10, 10, DIFF_HARD
, 1, NULL
},
486 { 12, 10, DIFF_HARD
, 2, NULL
},
487 { 7, 7, DIFF_HARD
, 3, NULL
},
488 { 9, 9, DIFF_HARD
, 4, NULL
},
489 { 5, 4, DIFF_HARD
, 5, NULL
},
490 { 7, 7, DIFF_HARD
, 6, NULL
},
491 { 5, 5, DIFF_HARD
, 7, NULL
},
495 static int game_fetch_preset(int i
, char **name
, game_params
**params
)
500 if (i
< 0 || i
>= lenof(presets
))
503 tmppar
= snew(game_params
);
504 *tmppar
= presets
[i
];
506 sprintf(buf
, "%dx%d %s - %s", tmppar
->h
, tmppar
->w
,
507 gridnames
[tmppar
->type
], diffnames
[tmppar
->diff
]);
513 static void free_params(game_params
*params
)
515 if (params
->game_grid
) {
516 grid_free(params
->game_grid
);
521 static void decode_params(game_params
*params
, char const *string
)
523 if (params
->game_grid
) {
524 grid_free(params
->game_grid
);
525 params
->game_grid
= NULL
;
527 params
->h
= params
->w
= atoi(string
);
528 params
->diff
= DIFF_EASY
;
529 while (*string
&& isdigit((unsigned char)*string
)) string
++;
530 if (*string
== 'x') {
532 params
->h
= atoi(string
);
533 while (*string
&& isdigit((unsigned char)*string
)) string
++;
535 if (*string
== 't') {
537 params
->type
= atoi(string
);
538 while (*string
&& isdigit((unsigned char)*string
)) string
++;
540 if (*string
== 'd') {
543 for (i
= 0; i
< DIFF_MAX
; i
++)
544 if (*string
== diffchars
[i
])
546 if (*string
) string
++;
550 static char *encode_params(game_params
*params
, int full
)
553 sprintf(str
, "%dx%dt%d", params
->w
, params
->h
, params
->type
);
555 sprintf(str
+ strlen(str
), "d%c", diffchars
[params
->diff
]);
559 static config_item
*game_configure(game_params
*params
)
564 ret
= snewn(5, config_item
);
566 ret
[0].name
= "Width";
567 ret
[0].type
= C_STRING
;
568 sprintf(buf
, "%d", params
->w
);
569 ret
[0].sval
= dupstr(buf
);
572 ret
[1].name
= "Height";
573 ret
[1].type
= C_STRING
;
574 sprintf(buf
, "%d", params
->h
);
575 ret
[1].sval
= dupstr(buf
);
578 ret
[2].name
= "Grid type";
579 ret
[2].type
= C_CHOICES
;
580 ret
[2].sval
= GRID_CONFIGS
;
581 ret
[2].ival
= params
->type
;
583 ret
[3].name
= "Difficulty";
584 ret
[3].type
= C_CHOICES
;
585 ret
[3].sval
= DIFFCONFIG
;
586 ret
[3].ival
= params
->diff
;
596 static game_params
*custom_params(config_item
*cfg
)
598 game_params
*ret
= snew(game_params
);
600 ret
->w
= atoi(cfg
[0].sval
);
601 ret
->h
= atoi(cfg
[1].sval
);
602 ret
->type
= cfg
[2].ival
;
603 ret
->diff
= cfg
[3].ival
;
605 ret
->game_grid
= NULL
;
609 static char *validate_params(game_params
*params
, int full
)
611 if (params
->w
< 3 || params
->h
< 3)
612 return "Width and height must both be at least 3";
613 if (params
->type
< 0 || params
->type
>= NUM_GRID_TYPES
)
614 return "Illegal grid type";
617 * This shouldn't be able to happen at all, since decode_params
618 * and custom_params will never generate anything that isn't
621 assert(params
->diff
< DIFF_MAX
);
626 /* Returns a newly allocated string describing the current puzzle */
627 static char *state_to_text(const game_state
*state
)
629 grid
*g
= state
->game_grid
;
631 int num_faces
= g
->num_faces
;
632 char *description
= snewn(num_faces
+ 1, char);
633 char *dp
= description
;
637 for (i
= 0; i
< num_faces
; i
++) {
638 if (state
->clues
[i
] < 0) {
639 if (empty_count
> 25) {
640 dp
+= sprintf(dp
, "%c", (int)(empty_count
+ 'a' - 1));
646 dp
+= sprintf(dp
, "%c", (int)(empty_count
+ 'a' - 1));
649 dp
+= sprintf(dp
, "%c", (int)CLUE2CHAR(state
->clues
[i
]));
654 dp
+= sprintf(dp
, "%c", (int)(empty_count
+ 'a' - 1));
656 retval
= dupstr(description
);
662 /* We require that the params pass the test in validate_params and that the
663 * description fills the entire game area */
664 static char *validate_desc(game_params
*params
, char *desc
)
668 params_generate_grid(params
);
669 g
= params
->game_grid
;
671 for (; *desc
; ++desc
) {
672 if (*desc
>= '0' && *desc
<= '9') {
677 count
+= *desc
- 'a' + 1;
680 return "Unknown character in description";
683 if (count
< g
->num_faces
)
684 return "Description too short for board size";
685 if (count
> g
->num_faces
)
686 return "Description too long for board size";
691 /* Sums the lengths of the numbers in range [0,n) */
692 /* See equivalent function in solo.c for justification of this. */
693 static int len_0_to_n(int n
)
695 int len
= 1; /* Counting 0 as a bit of a special case */
698 for (i
= 1; i
< n
; i
*= 10) {
699 len
+= max(n
- i
, 0);
705 static char *encode_solve_move(const game_state
*state
)
710 int num_edges
= state
->game_grid
->num_edges
;
712 /* This is going to return a string representing the moves needed to set
713 * every line in a grid to be the same as the ones in 'state'. The exact
714 * length of this string is predictable. */
716 len
= 1; /* Count the 'S' prefix */
717 /* Numbers in all lines */
718 len
+= len_0_to_n(num_edges
);
719 /* For each line we also have a letter */
722 ret
= snewn(len
+ 1, char);
725 p
+= sprintf(p
, "S");
727 for (i
= 0; i
< num_edges
; i
++) {
728 switch (state
->lines
[i
]) {
730 p
+= sprintf(p
, "%dy", i
);
733 p
+= sprintf(p
, "%dn", i
);
738 /* No point in doing sums like that if they're going to be wrong */
739 assert(strlen(ret
) <= (size_t)len
);
743 static game_ui
*new_ui(game_state
*state
)
748 static void free_ui(game_ui
*ui
)
752 static char *encode_ui(game_ui
*ui
)
757 static void decode_ui(game_ui
*ui
, char *encoding
)
761 static void game_changed_state(game_ui
*ui
, game_state
*oldstate
,
762 game_state
*newstate
)
766 static void game_compute_size(game_params
*params
, int tilesize
,
770 int grid_width
, grid_height
, rendered_width
, rendered_height
;
772 params_generate_grid(params
);
773 g
= params
->game_grid
;
774 grid_width
= g
->highest_x
- g
->lowest_x
;
775 grid_height
= g
->highest_y
- g
->lowest_y
;
776 /* multiply first to minimise rounding error on integer division */
777 rendered_width
= grid_width
* tilesize
/ g
->tilesize
;
778 rendered_height
= grid_height
* tilesize
/ g
->tilesize
;
779 *x
= rendered_width
+ 2 * BORDER(tilesize
) + 1;
780 *y
= rendered_height
+ 2 * BORDER(tilesize
) + 1;
783 static void game_set_size(drawing
*dr
, game_drawstate
*ds
,
784 game_params
*params
, int tilesize
)
786 ds
->tilesize
= tilesize
;
789 static float *game_colours(frontend
*fe
, int *ncolours
)
791 float *ret
= snewn(4 * NCOLOURS
, float);
793 frontend_default_colour(fe
, &ret
[COL_BACKGROUND
* 3]);
795 ret
[COL_FOREGROUND
* 3 + 0] = 0.0F
;
796 ret
[COL_FOREGROUND
* 3 + 1] = 0.0F
;
797 ret
[COL_FOREGROUND
* 3 + 2] = 0.0F
;
799 ret
[COL_LINEUNKNOWN
* 3 + 0] = 0.8F
;
800 ret
[COL_LINEUNKNOWN
* 3 + 1] = 0.8F
;
801 ret
[COL_LINEUNKNOWN
* 3 + 2] = 0.0F
;
803 ret
[COL_HIGHLIGHT
* 3 + 0] = 1.0F
;
804 ret
[COL_HIGHLIGHT
* 3 + 1] = 1.0F
;
805 ret
[COL_HIGHLIGHT
* 3 + 2] = 1.0F
;
807 ret
[COL_MISTAKE
* 3 + 0] = 1.0F
;
808 ret
[COL_MISTAKE
* 3 + 1] = 0.0F
;
809 ret
[COL_MISTAKE
* 3 + 2] = 0.0F
;
811 ret
[COL_SATISFIED
* 3 + 0] = 0.0F
;
812 ret
[COL_SATISFIED
* 3 + 1] = 0.0F
;
813 ret
[COL_SATISFIED
* 3 + 2] = 0.0F
;
815 *ncolours
= NCOLOURS
;
819 static game_drawstate
*game_new_drawstate(drawing
*dr
, game_state
*state
)
821 struct game_drawstate
*ds
= snew(struct game_drawstate
);
822 int num_faces
= state
->game_grid
->num_faces
;
823 int num_edges
= state
->game_grid
->num_edges
;
827 ds
->lines
= snewn(num_edges
, char);
828 ds
->clue_error
= snewn(num_faces
, char);
829 ds
->clue_satisfied
= snewn(num_faces
, char);
832 memset(ds
->lines
, LINE_UNKNOWN
, num_edges
);
833 memset(ds
->clue_error
, 0, num_faces
);
834 memset(ds
->clue_satisfied
, 0, num_faces
);
839 static void game_free_drawstate(drawing
*dr
, game_drawstate
*ds
)
841 sfree(ds
->clue_error
);
842 sfree(ds
->clue_satisfied
);
847 static int game_timing_state(game_state
*state
, game_ui
*ui
)
852 static float game_anim_length(game_state
*oldstate
, game_state
*newstate
,
853 int dir
, game_ui
*ui
)
858 static int game_can_format_as_text_now(game_params
*params
)
860 if (params
->type
!= 0)
865 static char *game_text_format(game_state
*state
)
871 grid
*g
= state
->game_grid
;
874 assert(state
->grid_type
== 0);
876 /* Work out the basic size unit */
877 f
= g
->faces
; /* first face */
878 assert(f
->order
== 4);
879 /* The dots are ordered clockwise, so the two opposite
880 * corners are guaranteed to span the square */
881 cell_size
= abs(f
->dots
[0]->x
- f
->dots
[2]->x
);
883 w
= (g
->highest_x
- g
->lowest_x
) / cell_size
;
884 h
= (g
->highest_y
- g
->lowest_y
) / cell_size
;
886 /* Create a blank "canvas" to "draw" on */
889 ret
= snewn(W
* H
+ 1, char);
890 for (y
= 0; y
< H
; y
++) {
891 for (x
= 0; x
< W
-1; x
++) {
894 ret
[y
*W
+ W
-1] = '\n';
898 /* Fill in edge info */
899 for (i
= 0; i
< g
->num_edges
; i
++) {
900 grid_edge
*e
= g
->edges
+ i
;
901 /* Cell coordinates, from (0,0) to (w-1,h-1) */
902 int x1
= (e
->dot1
->x
- g
->lowest_x
) / cell_size
;
903 int x2
= (e
->dot2
->x
- g
->lowest_x
) / cell_size
;
904 int y1
= (e
->dot1
->y
- g
->lowest_y
) / cell_size
;
905 int y2
= (e
->dot2
->y
- g
->lowest_y
) / cell_size
;
906 /* Midpoint, in canvas coordinates (canvas coordinates are just twice
907 * cell coordinates) */
910 switch (state
->lines
[i
]) {
912 ret
[y
*W
+ x
] = (y1
== y2
) ?
'-' : '|';
918 break; /* already a space */
920 assert(!"Illegal line state");
925 for (i
= 0; i
< g
->num_faces
; i
++) {
929 assert(f
->order
== 4);
930 /* Cell coordinates, from (0,0) to (w-1,h-1) */
931 x1
= (f
->dots
[0]->x
- g
->lowest_x
) / cell_size
;
932 x2
= (f
->dots
[2]->x
- g
->lowest_x
) / cell_size
;
933 y1
= (f
->dots
[0]->y
- g
->lowest_y
) / cell_size
;
934 y2
= (f
->dots
[2]->y
- g
->lowest_y
) / cell_size
;
935 /* Midpoint, in canvas coordinates */
938 ret
[y
*W
+ x
] = CLUE2CHAR(state
->clues
[i
]);
943 /* ----------------------------------------------------------------------
948 static void check_caches(const solver_state
* sstate
)
951 const game_state
*state
= sstate
->state
;
952 const grid
*g
= state
->game_grid
;
954 for (i
= 0; i
< g
->num_dots
; i
++) {
955 assert(dot_order(state
, i
, LINE_YES
) == sstate
->dot_yes_count
[i
]);
956 assert(dot_order(state
, i
, LINE_NO
) == sstate
->dot_no_count
[i
]);
959 for (i
= 0; i
< g
->num_faces
; i
++) {
960 assert(face_order(state
, i
, LINE_YES
) == sstate
->face_yes_count
[i
]);
961 assert(face_order(state
, i
, LINE_NO
) == sstate
->face_no_count
[i
]);
966 #define check_caches(s) \
968 fprintf(stderr, "check_caches at line %d\n", __LINE__); \
972 #endif /* DEBUG_CACHES */
974 /* ----------------------------------------------------------------------
975 * Solver utility functions
978 /* Sets the line (with index i) to the new state 'line_new', and updates
979 * the cached counts of any affected faces and dots.
980 * Returns TRUE if this actually changed the line's state. */
981 static int solver_set_line(solver_state
*sstate
, int i
,
982 enum line_state line_new
988 game_state
*state
= sstate
->state
;
992 assert(line_new
!= LINE_UNKNOWN
);
994 check_caches(sstate
);
996 if (state
->lines
[i
] == line_new
) {
997 return FALSE
; /* nothing changed */
999 state
->lines
[i
] = line_new
;
1002 fprintf(stderr
, "solver: set line [%d] to %s (%s)\n",
1003 i
, line_new
== LINE_YES ?
"YES" : "NO",
1007 g
= state
->game_grid
;
1010 /* Update the cache for both dots and both faces affected by this. */
1011 if (line_new
== LINE_YES
) {
1012 sstate
->dot_yes_count
[e
->dot1
- g
->dots
]++;
1013 sstate
->dot_yes_count
[e
->dot2
- g
->dots
]++;
1015 sstate
->face_yes_count
[e
->face1
- g
->faces
]++;
1018 sstate
->face_yes_count
[e
->face2
- g
->faces
]++;
1021 sstate
->dot_no_count
[e
->dot1
- g
->dots
]++;
1022 sstate
->dot_no_count
[e
->dot2
- g
->dots
]++;
1024 sstate
->face_no_count
[e
->face1
- g
->faces
]++;
1027 sstate
->face_no_count
[e
->face2
- g
->faces
]++;
1031 check_caches(sstate
);
1036 #define solver_set_line(a, b, c) \
1037 solver_set_line(a, b, c, __FUNCTION__)
1041 * Merge two dots due to the existence of an edge between them.
1042 * Updates the dsf tracking equivalence classes, and keeps track of
1043 * the length of path each dot is currently a part of.
1044 * Returns TRUE if the dots were already linked, ie if they are part of a
1045 * closed loop, and false otherwise.
1047 static int merge_dots(solver_state
*sstate
, int edge_index
)
1050 grid
*g
= sstate
->state
->game_grid
;
1051 grid_edge
*e
= g
->edges
+ edge_index
;
1053 i
= e
->dot1
- g
->dots
;
1054 j
= e
->dot2
- g
->dots
;
1056 i
= dsf_canonify(sstate
->dotdsf
, i
);
1057 j
= dsf_canonify(sstate
->dotdsf
, j
);
1062 len
= sstate
->looplen
[i
] + sstate
->looplen
[j
];
1063 dsf_merge(sstate
->dotdsf
, i
, j
);
1064 i
= dsf_canonify(sstate
->dotdsf
, i
);
1065 sstate
->looplen
[i
] = len
;
1070 /* Merge two lines because the solver has deduced that they must be either
1071 * identical or opposite. Returns TRUE if this is new information, otherwise
1073 static int merge_lines(solver_state
*sstate
, int i
, int j
, int inverse
1075 , const char *reason
1081 assert(i
< sstate
->state
->game_grid
->num_edges
);
1082 assert(j
< sstate
->state
->game_grid
->num_edges
);
1084 i
= edsf_canonify(sstate
->hard
->linedsf
, i
, &inv_tmp
);
1086 j
= edsf_canonify(sstate
->hard
->linedsf
, j
, &inv_tmp
);
1089 edsf_merge(sstate
->hard
->linedsf
, i
, j
, inverse
);
1093 fprintf(stderr
, "%s [%d] [%d] %s(%s)\n",
1095 inverse ?
"inverse " : "", reason
);
1102 #define merge_lines(a, b, c, d) \
1103 merge_lines(a, b, c, d, __FUNCTION__)
1106 /* Count the number of lines of a particular type currently going into the
1108 static int dot_order(const game_state
* state
, int dot
, char line_type
)
1111 grid
*g
= state
->game_grid
;
1112 grid_dot
*d
= g
->dots
+ dot
;
1115 for (i
= 0; i
< d
->order
; i
++) {
1116 grid_edge
*e
= d
->edges
[i
];
1117 if (state
->lines
[e
- g
->edges
] == line_type
)
1123 /* Count the number of lines of a particular type currently surrounding the
1125 static int face_order(const game_state
* state
, int face
, char line_type
)
1128 grid
*g
= state
->game_grid
;
1129 grid_face
*f
= g
->faces
+ face
;
1132 for (i
= 0; i
< f
->order
; i
++) {
1133 grid_edge
*e
= f
->edges
[i
];
1134 if (state
->lines
[e
- g
->edges
] == line_type
)
1140 /* Set all lines bordering a dot of type old_type to type new_type
1141 * Return value tells caller whether this function actually did anything */
1142 static int dot_setall(solver_state
*sstate
, int dot
,
1143 char old_type
, char new_type
)
1145 int retval
= FALSE
, r
;
1146 game_state
*state
= sstate
->state
;
1151 if (old_type
== new_type
)
1154 g
= state
->game_grid
;
1157 for (i
= 0; i
< d
->order
; i
++) {
1158 int line_index
= d
->edges
[i
] - g
->edges
;
1159 if (state
->lines
[line_index
] == old_type
) {
1160 r
= solver_set_line(sstate
, line_index
, new_type
);
1168 /* Set all lines bordering a face of type old_type to type new_type */
1169 static int face_setall(solver_state
*sstate
, int face
,
1170 char old_type
, char new_type
)
1172 int retval
= FALSE
, r
;
1173 game_state
*state
= sstate
->state
;
1178 if (old_type
== new_type
)
1181 g
= state
->game_grid
;
1182 f
= g
->faces
+ face
;
1184 for (i
= 0; i
< f
->order
; i
++) {
1185 int line_index
= f
->edges
[i
] - g
->edges
;
1186 if (state
->lines
[line_index
] == old_type
) {
1187 r
= solver_set_line(sstate
, line_index
, new_type
);
1195 /* ----------------------------------------------------------------------
1196 * Loop generation and clue removal
1199 /* We're going to store a list of current candidate faces for lighting.
1200 * Each face gets a 'score', which tells us how adding that face right
1201 * now would affect the length of the solution loop. We're trying to
1202 * maximise that quantity so will bias our random selection of faces to
1203 * light towards those with high scores */
1206 unsigned long random
;
1210 static int get_face_cmpfn(void *v1
, void *v2
)
1212 struct face
*f1
= v1
;
1213 struct face
*f2
= v2
;
1214 /* These grid_face pointers always point into the same list of
1215 * 'grid_face's, so it's valid to subtract them. */
1216 return f1
->f
- f2
->f
;
1219 static int face_sort_cmpfn(void *v1
, void *v2
)
1221 struct face
*f1
= v1
;
1222 struct face
*f2
= v2
;
1225 r
= f2
->score
- f1
->score
;
1230 if (f1
->random
< f2
->random
)
1232 else if (f1
->random
> f2
->random
)
1236 * It's _just_ possible that two faces might have been given
1237 * the same random value. In that situation, fall back to
1238 * comparing based on the positions within the grid's face-list.
1239 * This introduces a tiny directional bias, but not a significant one.
1241 return get_face_cmpfn(f1
, f2
);
1244 enum { FACE_LIT
, FACE_UNLIT
};
1246 /* face should be of type grid_face* here. */
1247 #define FACE_LIT_STATE(face) \
1248 ( (face) == NULL ? FACE_UNLIT : \
1249 board[(face) - g->faces] )
1251 /* 'board' is an array of these enums, indicating which faces are
1252 * currently lit. Returns whether it's legal to light up the
1254 static int can_light_face(grid
*g
, char* board
, int face_index
)
1257 grid_face
*test_face
= g
->faces
+ face_index
;
1258 grid_face
*starting_face
, *current_face
;
1260 int current_state
, s
;
1261 int found_lit_neighbour
= FALSE
;
1262 assert(board
[face_index
] == FACE_UNLIT
);
1264 /* Can only consider a face for lighting if it's adjacent to an
1265 * already lit face. */
1266 for (i
= 0; i
< test_face
->order
; i
++) {
1267 grid_edge
*e
= test_face
->edges
[i
];
1268 grid_face
*f
= (e
->face1
== test_face
) ? e
->face2
: e
->face1
;
1269 if (FACE_LIT_STATE(f
) == FACE_LIT
) {
1270 found_lit_neighbour
= TRUE
;
1274 if (!found_lit_neighbour
)
1277 /* Need to avoid creating a loop of lit faces around some unlit faces.
1278 * Also need to avoid meeting another lit face at a corner, with
1279 * unlit faces in between. Here's a simple test that (I believe) takes
1280 * care of both these conditions:
1282 * Take the circular path formed by this face's edges, and inflate it
1283 * slightly outwards. Imagine walking around this path and consider
1284 * the faces that you visit in sequence. This will include all faces
1285 * touching the given face, either along an edge or just at a corner.
1286 * Count the number of LIT/UNLIT transitions you encounter, as you walk
1287 * along the complete loop. This will obviously turn out to be an even
1289 * If 0, we're either in a completely unlit zone, or this face is a hole
1290 * in a completely lit zone. If the former, we would create a brand new
1291 * island by lighting this face. And the latter ought to be impossible -
1292 * it would mean there's already a lit loop, so something went wrong
1294 * If 4 or greater, there are too many separate lit regions touching this
1295 * face, and lighting it up would create a loop or a corner-violation.
1296 * The only allowed case is when the count is exactly 2. */
1298 /* i points to a dot around the test face.
1299 * j points to a face around the i^th dot.
1300 * The current face will always be:
1301 * test_face->dots[i]->faces[j]
1302 * We assume dots go clockwise around the test face,
1303 * and faces go clockwise around dots. */
1305 starting_face
= test_face
->dots
[0]->faces
[0];
1306 if (starting_face
== test_face
) {
1308 starting_face
= test_face
->dots
[0]->faces
[1];
1310 current_face
= starting_face
;
1312 current_state
= FACE_LIT_STATE(current_face
);
1315 /* Advance to next face.
1316 * Need to loop here because it might take several goes to
1320 if (j
== test_face
->dots
[i
]->order
)
1323 if (test_face
->dots
[i
]->faces
[j
] == test_face
) {
1324 /* Advance to next dot round test_face, then
1325 * find current_face around new dot
1326 * and advance to the next face clockwise */
1328 if (i
== test_face
->order
)
1330 for (j
= 0; j
< test_face
->dots
[i
]->order
; j
++) {
1331 if (test_face
->dots
[i
]->faces
[j
] == current_face
)
1334 /* Must actually find current_face around new dot,
1335 * or else something's wrong with the grid. */
1336 assert(j
!= test_face
->dots
[i
]->order
);
1337 /* Found, so advance to next face and try again */
1342 /* (i,j) are now advanced to next face */
1343 current_face
= test_face
->dots
[i
]->faces
[j
];
1344 s
= FACE_LIT_STATE(current_face
);
1345 if (s
!= current_state
) {
1348 if (transitions
> 2)
1349 return FALSE
; /* no point in continuing */
1351 } while (current_face
!= starting_face
);
1353 return (transitions
== 2) ? TRUE
: FALSE
;
1356 /* The 'score' of a face reflects its current desirability for selection
1357 * as the next face to light. We want to encourage moving into uncharted
1358 * areas so we give scores according to how many of the face's neighbours
1359 * are currently unlit. */
1360 static int face_score(grid
*g
, char *board
, grid_face
*face
)
1362 /* Simple formula: score = neighbours unlit - neighbours lit */
1363 int lit_count
= 0, unlit_count
= 0;
1367 for (i
= 0; i
< face
->order
; i
++) {
1369 f
= (e
->face1
== face
) ? e
->face2
: e
->face1
;
1370 if (FACE_LIT_STATE(f
) == FACE_LIT
)
1375 return unlit_count
- lit_count
;
1378 /* Generate a new complete set of clues for the given game_state. */
1379 static void add_full_clues(game_state
*state
, random_state
*rs
)
1381 signed char *clues
= state
->clues
;
1383 grid
*g
= state
->game_grid
;
1385 int num_faces
= g
->num_faces
;
1386 int first_time
= TRUE
;
1388 struct face
*face
, *tmpface
;
1389 struct face face_pos
;
1391 /* These will contain exactly the same information, sorted into different
1393 tree234
*lightable_faces_sorted
, *lightable_faces_gettable
;
1395 #define IS_LIGHTING_CANDIDATE(i) \
1396 (board[i] == FACE_UNLIT && \
1397 can_light_face(g, board, i))
1399 board
= snewn(num_faces
, char);
1402 memset(board
, FACE_UNLIT
, num_faces
);
1404 /* We need a way of favouring faces that will increase our loopiness.
1405 * We do this by maintaining a list of all candidate faces sorted by
1406 * their score and choose randomly from that with appropriate skew.
1407 * In order to avoid consistently biasing towards particular faces, we
1408 * need the sort order _within_ each group of scores to be completely
1409 * random. But it would be abusing the hospitality of the tree234 data
1410 * structure if our comparison function were nondeterministic :-). So with
1411 * each face we associate a random number that does not change during a
1412 * particular run of the generator, and use that as a secondary sort key.
1413 * Yes, this means we will be biased towards particular random faces in
1414 * any one run but that doesn't actually matter. */
1416 lightable_faces_sorted
= newtree234(face_sort_cmpfn
);
1417 lightable_faces_gettable
= newtree234(get_face_cmpfn
);
1418 #define ADD_FACE(f) \
1420 struct face *x = add234(lightable_faces_sorted, f); \
1422 x = add234(lightable_faces_gettable, f); \
1426 #define REMOVE_FACE(f) \
1428 struct face *x = del234(lightable_faces_sorted, f); \
1430 x = del234(lightable_faces_gettable, f); \
1434 /* Light faces one at a time until the board is interesting enough */
1439 /* lightable_faces_xxx are empty, so start the process by
1440 * lighting up the middle face. These tree234s should
1441 * remain empty, consistent with what would happen if
1442 * first_time were FALSE. */
1443 board
[g
->middle_face
- g
->faces
] = FACE_LIT
;
1444 face
= snew(struct face
);
1445 face
->f
= g
->middle_face
;
1446 /* No need to initialise any more of 'face' here, no other fields
1447 * are used in this case. */
1449 /* We have count234(lightable_faces_gettable) possibilities, and in
1450 * lightable_faces_sorted they are sorted with the most desirable
1452 c
= count234(lightable_faces_sorted
);
1455 assert(c
== count234(lightable_faces_gettable
));
1457 /* Check that the best face available is any good */
1458 face
= (struct face
*)index234(lightable_faces_sorted
, 0);
1462 * The situation for a general grid is slightly different from
1463 * a square grid. Decreasing the perimeter should be allowed
1464 * sometimes (think about creating a hexagon of lit triangles,
1465 * for example). For if it were _never_ done, then the user would
1466 * be able to illicitly deduce certain things. So we do it
1467 * sometimes but not always.
1469 if (face
->score
<= 0 && random_upto(rs
, 2) == 0) {
1473 assert(face
->f
); /* not the infinite face */
1474 assert(FACE_LIT_STATE(face
->f
) == FACE_UNLIT
);
1476 /* Update data structures */
1477 /* Light up the face and remove it from the lists */
1478 board
[face
->f
- g
->faces
] = FACE_LIT
;
1482 /* The face we've just lit up potentially affects the lightability
1483 * of any neighbouring faces (touching at a corner or edge). So the
1484 * search needs to be conducted around all faces touching the one
1485 * we've just lit. Iterate over its corners, then over each corner's
1487 for (i
= 0; i
< face
->f
->order
; i
++) {
1488 grid_dot
*d
= face
->f
->dots
[i
];
1489 for (j
= 0; j
< d
->order
; j
++) {
1490 grid_face
*f2
= d
->faces
[j
];
1496 tmpface
= find234(lightable_faces_gettable
, &face_pos
, NULL
);
1498 assert(tmpface
->f
== face_pos
.f
);
1499 assert(FACE_LIT_STATE(tmpface
->f
) == FACE_UNLIT
);
1500 REMOVE_FACE(tmpface
);
1502 tmpface
= snew(struct face
);
1503 tmpface
->f
= face_pos
.f
;
1504 tmpface
->random
= random_bits(rs
, 31);
1506 tmpface
->score
= face_score(g
, board
, tmpface
->f
);
1508 if (IS_LIGHTING_CANDIDATE(tmpface
->f
- g
->faces
)) {
1519 while ((face
= delpos234(lightable_faces_gettable
, 0)) != NULL
)
1521 freetree234(lightable_faces_gettable
);
1522 freetree234(lightable_faces_sorted
);
1524 /* Fill out all the clues by initialising to 0, then iterating over
1525 * all edges and incrementing each clue as we find edges that border
1526 * between LIT/UNLIT faces */
1527 memset(clues
, 0, num_faces
);
1528 for (i
= 0; i
< g
->num_edges
; i
++) {
1529 grid_edge
*e
= g
->edges
+ i
;
1530 grid_face
*f1
= e
->face1
;
1531 grid_face
*f2
= e
->face2
;
1532 if (FACE_LIT_STATE(f1
) != FACE_LIT_STATE(f2
)) {
1533 if (f1
) clues
[f1
- g
->faces
]++;
1534 if (f2
) clues
[f2
- g
->faces
]++;
1542 static int game_has_unique_soln(const game_state
*state
, int diff
)
1545 solver_state
*sstate_new
;
1546 solver_state
*sstate
= new_solver_state((game_state
*)state
, diff
);
1548 sstate_new
= solve_game_rec(sstate
, diff
);
1550 assert(sstate_new
->solver_status
!= SOLVER_MISTAKE
);
1551 ret
= (sstate_new
->solver_status
== SOLVER_SOLVED
);
1553 free_solver_state(sstate_new
);
1554 free_solver_state(sstate
);
1560 /* Remove clues one at a time at random. */
1561 static game_state
*remove_clues(game_state
*state
, random_state
*rs
,
1565 int num_faces
= state
->game_grid
->num_faces
;
1566 game_state
*ret
= dup_game(state
), *saved_ret
;
1569 /* We need to remove some clues. We'll do this by forming a list of all
1570 * available clues, shuffling it, then going along one at a
1571 * time clearing each clue in turn for which doing so doesn't render the
1572 * board unsolvable. */
1573 face_list
= snewn(num_faces
, int);
1574 for (n
= 0; n
< num_faces
; ++n
) {
1578 shuffle(face_list
, num_faces
, sizeof(int), rs
);
1580 for (n
= 0; n
< num_faces
; ++n
) {
1581 saved_ret
= dup_game(ret
);
1582 ret
->clues
[face_list
[n
]] = -1;
1584 if (game_has_unique_soln(ret
, diff
)) {
1585 free_game(saved_ret
);
1597 static char *new_game_desc(game_params
*params
, random_state
*rs
,
1598 char **aux
, int interactive
)
1600 /* solution and description both use run-length encoding in obvious ways */
1603 game_state
*state
= snew(game_state
);
1604 game_state
*state_new
;
1605 params_generate_grid(params
);
1606 state
->game_grid
= g
= params
->game_grid
;
1608 state
->clues
= snewn(g
->num_faces
, signed char);
1609 state
->lines
= snewn(g
->num_edges
, char);
1611 state
->grid_type
= params
->type
;
1615 memset(state
->lines
, LINE_UNKNOWN
, g
->num_edges
);
1617 state
->solved
= state
->cheated
= FALSE
;
1619 /* Get a new random solvable board with all its clues filled in. Yes, this
1620 * can loop for ever if the params are suitably unfavourable, but
1621 * preventing games smaller than 4x4 seems to stop this happening */
1623 add_full_clues(state
, rs
);
1624 } while (!game_has_unique_soln(state
, params
->diff
));
1626 state_new
= remove_clues(state
, rs
, params
->diff
);
1631 if (params
->diff
> 0 && game_has_unique_soln(state
, params
->diff
-1)) {
1633 fprintf(stderr
, "Rejecting board, it is too easy\n");
1635 goto newboard_please
;
1638 retval
= state_to_text(state
);
1642 assert(!validate_desc(params
, retval
));
1647 static game_state
*new_game(midend
*me
, game_params
*params
, char *desc
)
1650 game_state
*state
= snew(game_state
);
1651 int empties_to_make
= 0;
1653 const char *dp
= desc
;
1655 int num_faces
, num_edges
;
1657 params_generate_grid(params
);
1658 state
->game_grid
= g
= params
->game_grid
;
1660 num_faces
= g
->num_faces
;
1661 num_edges
= g
->num_edges
;
1663 state
->clues
= snewn(num_faces
, signed char);
1664 state
->lines
= snewn(num_edges
, char);
1666 state
->solved
= state
->cheated
= FALSE
;
1668 state
->grid_type
= params
->type
;
1670 for (i
= 0; i
< num_faces
; i
++) {
1671 if (empties_to_make
) {
1673 state
->clues
[i
] = -1;
1679 if (n
>= 0 && n
< 10) {
1680 state
->clues
[i
] = n
;
1684 state
->clues
[i
] = -1;
1685 empties_to_make
= n
- 1;
1690 memset(state
->lines
, LINE_UNKNOWN
, num_edges
);
1695 enum { LOOP_NONE
=0, LOOP_SOLN
, LOOP_NOT_SOLN
};
1697 /* ----------------------------------------------------------------------
1700 * Our solver modes operate as follows. Each mode also uses the modes above it.
1703 * Just implement the rules of the game.
1706 * For each (adjacent) pair of lines through each dot we store a bit for
1707 * whether at least one of them is on and whether at most one is on. (If we
1708 * know both or neither is on that's already stored more directly.)
1711 * Use edsf data structure to make equivalence classes of lines that are
1712 * known identical to or opposite to one another.
1717 * For general grids, we consider "dlines" to be pairs of lines joined
1718 * at a dot. The lines must be adjacent around the dot, so we can think of
1719 * a dline as being a dot+face combination. Or, a dot+edge combination where
1720 * the second edge is taken to be the next clockwise edge from the dot.
1721 * Original loopy code didn't have this extra restriction of the lines being
1722 * adjacent. From my tests with square grids, this extra restriction seems to
1723 * take little, if anything, away from the quality of the puzzles.
1724 * A dline can be uniquely identified by an edge/dot combination, given that
1725 * a dline-pair always goes clockwise around its common dot. The edge/dot
1726 * combination can be represented by an edge/bool combination - if bool is
1727 * TRUE, use edge->dot1 else use edge->dot2. So the total number of dlines is
1728 * exactly twice the number of edges in the grid - although the dlines
1729 * spanning the infinite face are not all that useful to the solver.
1730 * Note that, by convention, a dline goes clockwise around its common dot,
1731 * which means the dline goes anti-clockwise around its common face.
1734 /* Helper functions for obtaining an index into an array of dlines, given
1735 * various information. We assume the grid layout conventions about how
1736 * the various lists are interleaved - see grid_make_consistent() for
1739 /* i points to the first edge of the dline pair, reading clockwise around
1741 static int dline_index_from_dot(grid
*g
, grid_dot
*d
, int i
)
1743 grid_edge
*e
= d
->edges
[i
];
1748 if (i2
== d
->order
) i2
= 0;
1751 ret
= 2 * (e
- g
->edges
) + ((e
->dot1
== d
) ?
1 : 0);
1753 printf("dline_index_from_dot: d=%d,i=%d, edges [%d,%d] - %d\n",
1754 (int)(d
- g
->dots
), i
, (int)(e
- g
->edges
),
1755 (int)(e2
- g
->edges
), ret
);
1759 /* i points to the second edge of the dline pair, reading clockwise around
1760 * the face. That is, the edges of the dline, starting at edge{i}, read
1761 * anti-clockwise around the face. By layout conventions, the common dot
1762 * of the dline will be f->dots[i] */
1763 static int dline_index_from_face(grid
*g
, grid_face
*f
, int i
)
1765 grid_edge
*e
= f
->edges
[i
];
1766 grid_dot
*d
= f
->dots
[i
];
1771 if (i2
< 0) i2
+= f
->order
;
1774 ret
= 2 * (e
- g
->edges
) + ((e
->dot1
== d
) ?
1 : 0);
1776 printf("dline_index_from_face: f=%d,i=%d, edges [%d,%d] - %d\n",
1777 (int)(f
- g
->faces
), i
, (int)(e
- g
->edges
),
1778 (int)(e2
- g
->edges
), ret
);
1782 static int is_atleastone(const char *dline_array
, int index
)
1784 return BIT_SET(dline_array
[index
], 0);
1786 static int set_atleastone(char *dline_array
, int index
)
1788 return SET_BIT(dline_array
[index
], 0);
1790 static int is_atmostone(const char *dline_array
, int index
)
1792 return BIT_SET(dline_array
[index
], 1);
1794 static int set_atmostone(char *dline_array
, int index
)
1796 return SET_BIT(dline_array
[index
], 1);
1799 static void array_setall(char *array
, char from
, char to
, int len
)
1801 char *p
= array
, *p_old
= p
;
1802 int len_remaining
= len
;
1804 while ((p
= memchr(p
, from
, len_remaining
))) {
1806 len_remaining
-= p
- p_old
;
1811 /* Helper, called when doing dline dot deductions, in the case where we
1812 * have 4 UNKNOWNs, and two of them (adjacent) have *exactly* one YES between
1813 * them (because of dline atmostone/atleastone).
1814 * On entry, edge points to the first of these two UNKNOWNs. This function
1815 * will find the opposite UNKNOWNS (if they are adjacent to one another)
1816 * and set their corresponding dline to atleastone. (Setting atmostone
1817 * already happens in earlier dline deductions) */
1818 static int dline_set_opp_atleastone(solver_state
*sstate
,
1819 grid_dot
*d
, int edge
)
1821 game_state
*state
= sstate
->state
;
1822 grid
*g
= state
->game_grid
;
1825 for (opp
= 0; opp
< N
; opp
++) {
1826 int opp_dline_index
;
1827 if (opp
== edge
|| opp
== edge
+1 || opp
== edge
-1)
1829 if (opp
== 0 && edge
== N
-1)
1831 if (opp
== N
-1 && edge
== 0)
1834 if (opp2
== N
) opp2
= 0;
1835 /* Check if opp, opp2 point to LINE_UNKNOWNs */
1836 if (state
->lines
[d
->edges
[opp
] - g
->edges
] != LINE_UNKNOWN
)
1838 if (state
->lines
[d
->edges
[opp2
] - g
->edges
] != LINE_UNKNOWN
)
1840 /* Found opposite UNKNOWNS and they're next to each other */
1841 opp_dline_index
= dline_index_from_dot(g
, d
, opp
);
1842 return set_atleastone(sstate
->normal
->dlines
, opp_dline_index
);
1848 /* Set pairs of lines around this face which are known to be identical, to
1849 * the given line_state */
1850 static int face_setall_identical(solver_state
*sstate
, int face_index
,
1851 enum line_state line_new
)
1853 /* can[dir] contains the canonical line associated with the line in
1854 * direction dir from the square in question. Similarly inv[dir] is
1855 * whether or not the line in question is inverse to its canonical
1858 game_state
*state
= sstate
->state
;
1859 grid
*g
= state
->game_grid
;
1860 grid_face
*f
= g
->faces
+ face_index
;
1863 int can1
, can2
, inv1
, inv2
;
1865 for (i
= 0; i
< N
; i
++) {
1866 int line1_index
= f
->edges
[i
] - g
->edges
;
1867 if (state
->lines
[line1_index
] != LINE_UNKNOWN
)
1869 for (j
= i
+ 1; j
< N
; j
++) {
1870 int line2_index
= f
->edges
[j
] - g
->edges
;
1871 if (state
->lines
[line2_index
] != LINE_UNKNOWN
)
1874 /* Found two UNKNOWNS */
1875 can1
= edsf_canonify(sstate
->hard
->linedsf
, line1_index
, &inv1
);
1876 can2
= edsf_canonify(sstate
->hard
->linedsf
, line2_index
, &inv2
);
1877 if (can1
== can2
&& inv1
== inv2
) {
1878 solver_set_line(sstate
, line1_index
, line_new
);
1879 solver_set_line(sstate
, line2_index
, line_new
);
1886 /* Given a dot or face, and a count of LINE_UNKNOWNs, find them and
1887 * return the edge indices into e. */
1888 static void find_unknowns(game_state
*state
,
1889 grid_edge
**edge_list
, /* Edge list to search (from a face or a dot) */
1890 int expected_count
, /* Number of UNKNOWNs (comes from solver's cache) */
1891 int *e
/* Returned edge indices */)
1894 grid
*g
= state
->game_grid
;
1895 while (c
< expected_count
) {
1896 int line_index
= *edge_list
- g
->edges
;
1897 if (state
->lines
[line_index
] == LINE_UNKNOWN
) {
1905 /* If we have a list of edges, and we know whether the number of YESs should
1906 * be odd or even, and there are only a few UNKNOWNs, we can do some simple
1907 * linedsf deductions. This can be used for both face and dot deductions.
1908 * Returns the difficulty level of the next solver that should be used,
1909 * or DIFF_MAX if no progress was made. */
1910 static int parity_deductions(solver_state
*sstate
,
1911 grid_edge
**edge_list
, /* Edge list (from a face or a dot) */
1912 int total_parity
, /* Expected number of YESs modulo 2 (either 0 or 1) */
1915 game_state
*state
= sstate
->state
;
1916 int diff
= DIFF_MAX
;
1917 int *linedsf
= sstate
->hard
->linedsf
;
1919 if (unknown_count
== 2) {
1920 /* Lines are known alike/opposite, depending on inv. */
1922 find_unknowns(state
, edge_list
, 2, e
);
1923 if (merge_lines(sstate
, e
[0], e
[1], total_parity
))
1924 diff
= min(diff
, DIFF_HARD
);
1925 } else if (unknown_count
== 3) {
1927 int can
[3]; /* canonical edges */
1928 int inv
[3]; /* whether can[x] is inverse to e[x] */
1929 find_unknowns(state
, edge_list
, 3, e
);
1930 can
[0] = edsf_canonify(linedsf
, e
[0], inv
);
1931 can
[1] = edsf_canonify(linedsf
, e
[1], inv
+1);
1932 can
[2] = edsf_canonify(linedsf
, e
[2], inv
+2);
1933 if (can
[0] == can
[1]) {
1934 if (solver_set_line(sstate
, e
[2], (total_parity
^inv
[0]^inv
[1]) ?
1935 LINE_YES
: LINE_NO
))
1936 diff
= min(diff
, DIFF_EASY
);
1938 if (can
[0] == can
[2]) {
1939 if (solver_set_line(sstate
, e
[1], (total_parity
^inv
[0]^inv
[2]) ?
1940 LINE_YES
: LINE_NO
))
1941 diff
= min(diff
, DIFF_EASY
);
1943 if (can
[1] == can
[2]) {
1944 if (solver_set_line(sstate
, e
[0], (total_parity
^inv
[1]^inv
[2]) ?
1945 LINE_YES
: LINE_NO
))
1946 diff
= min(diff
, DIFF_EASY
);
1948 } else if (unknown_count
== 4) {
1950 int can
[4]; /* canonical edges */
1951 int inv
[4]; /* whether can[x] is inverse to e[x] */
1952 find_unknowns(state
, edge_list
, 4, e
);
1953 can
[0] = edsf_canonify(linedsf
, e
[0], inv
);
1954 can
[1] = edsf_canonify(linedsf
, e
[1], inv
+1);
1955 can
[2] = edsf_canonify(linedsf
, e
[2], inv
+2);
1956 can
[3] = edsf_canonify(linedsf
, e
[3], inv
+3);
1957 if (can
[0] == can
[1]) {
1958 if (merge_lines(sstate
, e
[2], e
[3], total_parity
^inv
[0]^inv
[1]))
1959 diff
= min(diff
, DIFF_HARD
);
1960 } else if (can
[0] == can
[2]) {
1961 if (merge_lines(sstate
, e
[1], e
[3], total_parity
^inv
[0]^inv
[2]))
1962 diff
= min(diff
, DIFF_HARD
);
1963 } else if (can
[0] == can
[3]) {
1964 if (merge_lines(sstate
, e
[1], e
[2], total_parity
^inv
[0]^inv
[3]))
1965 diff
= min(diff
, DIFF_HARD
);
1966 } else if (can
[1] == can
[2]) {
1967 if (merge_lines(sstate
, e
[0], e
[3], total_parity
^inv
[1]^inv
[2]))
1968 diff
= min(diff
, DIFF_HARD
);
1969 } else if (can
[1] == can
[3]) {
1970 if (merge_lines(sstate
, e
[0], e
[2], total_parity
^inv
[1]^inv
[3]))
1971 diff
= min(diff
, DIFF_HARD
);
1972 } else if (can
[2] == can
[3]) {
1973 if (merge_lines(sstate
, e
[0], e
[1], total_parity
^inv
[2]^inv
[3]))
1974 diff
= min(diff
, DIFF_HARD
);
1982 * These are the main solver functions.
1984 * Their return values are diff values corresponding to the lowest mode solver
1985 * that would notice the work that they have done. For example if the normal
1986 * mode solver adds actual lines or crosses, it will return DIFF_EASY as the
1987 * easy mode solver might be able to make progress using that. It doesn't make
1988 * sense for one of them to return a diff value higher than that of the
1991 * Each function returns the lowest value it can, as early as possible, in
1992 * order to try and pass as much work as possible back to the lower level
1993 * solvers which progress more quickly.
1996 /* PROPOSED NEW DESIGN:
1997 * We have a work queue consisting of 'events' notifying us that something has
1998 * happened that a particular solver mode might be interested in. For example
1999 * the hard mode solver might do something that helps the normal mode solver at
2000 * dot [x,y] in which case it will enqueue an event recording this fact. Then
2001 * we pull events off the work queue, and hand each in turn to the solver that
2002 * is interested in them. If a solver reports that it failed we pass the same
2003 * event on to progressively more advanced solvers and the loop detector. Once
2004 * we've exhausted an event, or it has helped us progress, we drop it and
2005 * continue to the next one. The events are sorted first in order of solver
2006 * complexity (easy first) then order of insertion (oldest first).
2007 * Once we run out of events we loop over each permitted solver in turn
2008 * (easiest first) until either a deduction is made (and an event therefore
2009 * emerges) or no further deductions can be made (in which case we've failed).
2012 * * How do we 'loop over' a solver when both dots and squares are concerned.
2013 * Answer: first all squares then all dots.
2016 static int easy_mode_deductions(solver_state
*sstate
)
2018 int i
, current_yes
, current_no
;
2019 game_state
*state
= sstate
->state
;
2020 grid
*g
= state
->game_grid
;
2021 int diff
= DIFF_MAX
;
2023 /* Per-face deductions */
2024 for (i
= 0; i
< g
->num_faces
; i
++) {
2025 grid_face
*f
= g
->faces
+ i
;
2027 if (sstate
->face_solved
[i
])
2030 current_yes
= sstate
->face_yes_count
[i
];
2031 current_no
= sstate
->face_no_count
[i
];
2033 if (current_yes
+ current_no
== f
->order
) {
2034 sstate
->face_solved
[i
] = TRUE
;
2038 if (state
->clues
[i
] < 0)
2041 if (state
->clues
[i
] < current_yes
) {
2042 sstate
->solver_status
= SOLVER_MISTAKE
;
2045 if (state
->clues
[i
] == current_yes
) {
2046 if (face_setall(sstate
, i
, LINE_UNKNOWN
, LINE_NO
))
2047 diff
= min(diff
, DIFF_EASY
);
2048 sstate
->face_solved
[i
] = TRUE
;
2052 if (f
->order
- state
->clues
[i
] < current_no
) {
2053 sstate
->solver_status
= SOLVER_MISTAKE
;
2056 if (f
->order
- state
->clues
[i
] == current_no
) {
2057 if (face_setall(sstate
, i
, LINE_UNKNOWN
, LINE_YES
))
2058 diff
= min(diff
, DIFF_EASY
);
2059 sstate
->face_solved
[i
] = TRUE
;
2064 check_caches(sstate
);
2066 /* Per-dot deductions */
2067 for (i
= 0; i
< g
->num_dots
; i
++) {
2068 grid_dot
*d
= g
->dots
+ i
;
2069 int yes
, no
, unknown
;
2071 if (sstate
->dot_solved
[i
])
2074 yes
= sstate
->dot_yes_count
[i
];
2075 no
= sstate
->dot_no_count
[i
];
2076 unknown
= d
->order
- yes
- no
;
2080 sstate
->dot_solved
[i
] = TRUE
;
2081 } else if (unknown
== 1) {
2082 dot_setall(sstate
, i
, LINE_UNKNOWN
, LINE_NO
);
2083 diff
= min(diff
, DIFF_EASY
);
2084 sstate
->dot_solved
[i
] = TRUE
;
2086 } else if (yes
== 1) {
2088 sstate
->solver_status
= SOLVER_MISTAKE
;
2090 } else if (unknown
== 1) {
2091 dot_setall(sstate
, i
, LINE_UNKNOWN
, LINE_YES
);
2092 diff
= min(diff
, DIFF_EASY
);
2094 } else if (yes
== 2) {
2096 dot_setall(sstate
, i
, LINE_UNKNOWN
, LINE_NO
);
2097 diff
= min(diff
, DIFF_EASY
);
2099 sstate
->dot_solved
[i
] = TRUE
;
2101 sstate
->solver_status
= SOLVER_MISTAKE
;
2106 check_caches(sstate
);
2111 static int normal_mode_deductions(solver_state
*sstate
)
2113 game_state
*state
= sstate
->state
;
2114 grid
*g
= state
->game_grid
;
2115 char *dlines
= sstate
->normal
->dlines
;
2117 int diff
= DIFF_MAX
;
2119 /* ------ Face deductions ------ */
2121 /* Given a set of dline atmostone/atleastone constraints, need to figure
2122 * out if we can deduce any further info. For more general faces than
2123 * squares, this turns out to be a tricky problem.
2124 * The approach taken here is to define (per face) NxN matrices:
2125 * "maxs" and "mins".
2126 * The entries maxs(j,k) and mins(j,k) define the upper and lower limits
2127 * for the possible number of edges that are YES between positions j and k
2128 * going clockwise around the face. Can think of j and k as marking dots
2129 * around the face (recall the labelling scheme: edge0 joins dot0 to dot1,
2130 * edge1 joins dot1 to dot2 etc).
2131 * Trivially, mins(j,j) = maxs(j,j) = 0, and we don't even bother storing
2132 * these. mins(j,j+1) and maxs(j,j+1) are determined by whether edge{j}
2133 * is YES, NO or UNKNOWN. mins(j,j+2) and maxs(j,j+2) are related to
2134 * the dline atmostone/atleastone status for edges j and j+1.
2136 * Then we calculate the remaining entries recursively. We definitely
2138 * mins(j,k) >= { mins(j,u) + mins(u,k) } for any u between j and k.
2139 * This is because any valid placement of YESs between j and k must give
2140 * a valid placement between j and u, and also between u and k.
2141 * I believe it's sufficient to use just the two values of u:
2142 * j+1 and j+2. Seems to work well in practice - the bounds we compute
2143 * are rigorous, even if they might not be best-possible.
2145 * Once we have maxs and mins calculated, we can make inferences about
2146 * each dline{j,j+1} by looking at the possible complementary edge-counts
2147 * mins(j+2,j) and maxs(j+2,j) and comparing these with the face clue.
2148 * As well as dlines, we can make similar inferences about single edges.
2149 * For example, consider a pentagon with clue 3, and we know at most one
2150 * of (edge0, edge1) is YES, and at most one of (edge2, edge3) is YES.
2151 * We could then deduce edge4 is YES, because maxs(0,4) would be 2, so
2152 * that final edge would have to be YES to make the count up to 3.
2155 /* Much quicker to allocate arrays on the stack than the heap, so
2156 * define the largest possible face size, and base our array allocations
2157 * on that. We check this with an assertion, in case someone decides to
2158 * make a grid which has larger faces than this. Note, this algorithm
2159 * could get quite expensive if there are many large faces. */
2160 #define MAX_FACE_SIZE 8
2162 for (i
= 0; i
< g
->num_faces
; i
++) {
2163 int maxs
[MAX_FACE_SIZE
][MAX_FACE_SIZE
];
2164 int mins
[MAX_FACE_SIZE
][MAX_FACE_SIZE
];
2165 grid_face
*f
= g
->faces
+ i
;
2168 int clue
= state
->clues
[i
];
2169 assert(N
<= MAX_FACE_SIZE
);
2170 if (sstate
->face_solved
[i
])
2172 if (clue
< 0) continue;
2174 /* Calculate the (j,j+1) entries */
2175 for (j
= 0; j
< N
; j
++) {
2176 int edge_index
= f
->edges
[j
] - g
->edges
;
2178 enum line_state line1
= state
->lines
[edge_index
];
2179 enum line_state line2
;
2183 maxs
[j
][k
] = (line1
== LINE_NO
) ?
0 : 1;
2184 mins
[j
][k
] = (line1
== LINE_YES
) ?
1 : 0;
2185 /* Calculate the (j,j+2) entries */
2186 dline_index
= dline_index_from_face(g
, f
, k
);
2187 edge_index
= f
->edges
[k
] - g
->edges
;
2188 line2
= state
->lines
[edge_index
];
2194 if (line1
== LINE_NO
) tmp
--;
2195 if (line2
== LINE_NO
) tmp
--;
2196 if (tmp
== 2 && is_atmostone(dlines
, dline_index
))
2202 if (line1
== LINE_YES
) tmp
++;
2203 if (line2
== LINE_YES
) tmp
++;
2204 if (tmp
== 0 && is_atleastone(dlines
, dline_index
))
2209 /* Calculate the (j,j+m) entries for m between 3 and N-1 */
2210 for (m
= 3; m
< N
; m
++) {
2211 for (j
= 0; j
< N
; j
++) {
2219 maxs
[j
][k
] = maxs
[j
][u
] + maxs
[u
][k
];
2220 mins
[j
][k
] = mins
[j
][u
] + mins
[u
][k
];
2221 tmp
= maxs
[j
][v
] + maxs
[v
][k
];
2222 maxs
[j
][k
] = min(maxs
[j
][k
], tmp
);
2223 tmp
= mins
[j
][v
] + mins
[v
][k
];
2224 mins
[j
][k
] = max(mins
[j
][k
], tmp
);
2228 /* See if we can make any deductions */
2229 for (j
= 0; j
< N
; j
++) {
2231 grid_edge
*e
= f
->edges
[j
];
2232 int line_index
= e
- g
->edges
;
2235 if (state
->lines
[line_index
] != LINE_UNKNOWN
)
2240 /* minimum YESs in the complement of this edge */
2241 if (mins
[k
][j
] > clue
) {
2242 sstate
->solver_status
= SOLVER_MISTAKE
;
2245 if (mins
[k
][j
] == clue
) {
2246 /* setting this edge to YES would make at least
2247 * (clue+1) edges - contradiction */
2248 solver_set_line(sstate
, line_index
, LINE_NO
);
2249 diff
= min(diff
, DIFF_EASY
);
2251 if (maxs
[k
][j
] < clue
- 1) {
2252 sstate
->solver_status
= SOLVER_MISTAKE
;
2255 if (maxs
[k
][j
] == clue
- 1) {
2256 /* Only way to satisfy the clue is to set edge{j} as YES */
2257 solver_set_line(sstate
, line_index
, LINE_YES
);
2258 diff
= min(diff
, DIFF_EASY
);
2261 /* Now see if we can make dline deduction for edges{j,j+1} */
2263 if (state
->lines
[e
- g
->edges
] != LINE_UNKNOWN
)
2264 /* Only worth doing this for an UNKNOWN,UNKNOWN pair.
2265 * Dlines where one of the edges is known, are handled in the
2269 dline_index
= dline_index_from_face(g
, f
, k
);
2273 /* minimum YESs in the complement of this dline */
2274 if (mins
[k
][j
] > clue
- 2) {
2275 /* Adding 2 YESs would break the clue */
2276 if (set_atmostone(dlines
, dline_index
))
2277 diff
= min(diff
, DIFF_NORMAL
);
2279 /* maximum YESs in the complement of this dline */
2280 if (maxs
[k
][j
] < clue
) {
2281 /* Adding 2 NOs would mean not enough YESs */
2282 if (set_atleastone(dlines
, dline_index
))
2283 diff
= min(diff
, DIFF_NORMAL
);
2288 if (diff
< DIFF_NORMAL
)
2291 /* ------ Dot deductions ------ */
2293 for (i
= 0; i
< g
->num_dots
; i
++) {
2294 grid_dot
*d
= g
->dots
+ i
;
2296 int yes
, no
, unknown
;
2298 if (sstate
->dot_solved
[i
])
2300 yes
= sstate
->dot_yes_count
[i
];
2301 no
= sstate
->dot_no_count
[i
];
2302 unknown
= N
- yes
- no
;
2304 for (j
= 0; j
< N
; j
++) {
2307 int line1_index
, line2_index
;
2308 enum line_state line1
, line2
;
2311 dline_index
= dline_index_from_dot(g
, d
, j
);
2312 line1_index
= d
->edges
[j
] - g
->edges
;
2313 line2_index
= d
->edges
[k
] - g
->edges
;
2314 line1
= state
->lines
[line1_index
];
2315 line2
= state
->lines
[line2_index
];
2317 /* Infer dline state from line state */
2318 if (line1
== LINE_NO
|| line2
== LINE_NO
) {
2319 if (set_atmostone(dlines
, dline_index
))
2320 diff
= min(diff
, DIFF_NORMAL
);
2322 if (line1
== LINE_YES
|| line2
== LINE_YES
) {
2323 if (set_atleastone(dlines
, dline_index
))
2324 diff
= min(diff
, DIFF_NORMAL
);
2326 /* Infer line state from dline state */
2327 if (is_atmostone(dlines
, dline_index
)) {
2328 if (line1
== LINE_YES
&& line2
== LINE_UNKNOWN
) {
2329 solver_set_line(sstate
, line2_index
, LINE_NO
);
2330 diff
= min(diff
, DIFF_EASY
);
2332 if (line2
== LINE_YES
&& line1
== LINE_UNKNOWN
) {
2333 solver_set_line(sstate
, line1_index
, LINE_NO
);
2334 diff
= min(diff
, DIFF_EASY
);
2337 if (is_atleastone(dlines
, dline_index
)) {
2338 if (line1
== LINE_NO
&& line2
== LINE_UNKNOWN
) {
2339 solver_set_line(sstate
, line2_index
, LINE_YES
);
2340 diff
= min(diff
, DIFF_EASY
);
2342 if (line2
== LINE_NO
&& line1
== LINE_UNKNOWN
) {
2343 solver_set_line(sstate
, line1_index
, LINE_YES
);
2344 diff
= min(diff
, DIFF_EASY
);
2347 /* Deductions that depend on the numbers of lines.
2348 * Only bother if both lines are UNKNOWN, otherwise the
2349 * easy-mode solver (or deductions above) would have taken
2351 if (line1
!= LINE_UNKNOWN
|| line2
!= LINE_UNKNOWN
)
2354 if (yes
== 0 && unknown
== 2) {
2355 /* Both these unknowns must be identical. If we know
2356 * atmostone or atleastone, we can make progress. */
2357 if (is_atmostone(dlines
, dline_index
)) {
2358 solver_set_line(sstate
, line1_index
, LINE_NO
);
2359 solver_set_line(sstate
, line2_index
, LINE_NO
);
2360 diff
= min(diff
, DIFF_EASY
);
2362 if (is_atleastone(dlines
, dline_index
)) {
2363 solver_set_line(sstate
, line1_index
, LINE_YES
);
2364 solver_set_line(sstate
, line2_index
, LINE_YES
);
2365 diff
= min(diff
, DIFF_EASY
);
2369 if (set_atmostone(dlines
, dline_index
))
2370 diff
= min(diff
, DIFF_NORMAL
);
2372 if (set_atleastone(dlines
, dline_index
))
2373 diff
= min(diff
, DIFF_NORMAL
);
2377 /* If we have atleastone set for this dline, infer
2378 * atmostone for each "opposite" dline (that is, each
2379 * dline without edges in common with this one).
2380 * Again, this test is only worth doing if both these
2381 * lines are UNKNOWN. For if one of these lines were YES,
2382 * the (yes == 1) test above would kick in instead. */
2383 if (is_atleastone(dlines
, dline_index
)) {
2385 for (opp
= 0; opp
< N
; opp
++) {
2386 int opp_dline_index
;
2387 if (opp
== j
|| opp
== j
+1 || opp
== j
-1)
2389 if (j
== 0 && opp
== N
-1)
2391 if (j
== N
-1 && opp
== 0)
2393 opp_dline_index
= dline_index_from_dot(g
, d
, opp
);
2394 if (set_atmostone(dlines
, opp_dline_index
))
2395 diff
= min(diff
, DIFF_NORMAL
);
2398 if (yes
== 0 && is_atmostone(dlines
, dline_index
)) {
2399 /* This dline has *exactly* one YES and there are no
2400 * other YESs. This allows more deductions. */
2402 /* Third unknown must be YES */
2403 for (opp
= 0; opp
< N
; opp
++) {
2405 if (opp
== j
|| opp
== k
)
2407 opp_index
= d
->edges
[opp
] - g
->edges
;
2408 if (state
->lines
[opp_index
] == LINE_UNKNOWN
) {
2409 solver_set_line(sstate
, opp_index
, LINE_YES
);
2410 diff
= min(diff
, DIFF_EASY
);
2413 } else if (unknown
== 4) {
2414 /* Exactly one of opposite UNKNOWNS is YES. We've
2415 * already set atmostone, so set atleastone as well.
2417 if (dline_set_opp_atleastone(sstate
, d
, j
))
2418 diff
= min(diff
, DIFF_NORMAL
);
2427 static int hard_mode_deductions(solver_state
*sstate
)
2429 game_state
*state
= sstate
->state
;
2430 grid
*g
= state
->game_grid
;
2431 char *dlines
= sstate
->normal
->dlines
;
2433 int diff
= DIFF_MAX
;
2436 /* ------ Face deductions ------ */
2438 /* A fully-general linedsf deduction seems overly complicated
2439 * (I suspect the problem is NP-complete, though in practice it might just
2440 * be doable because faces are limited in size).
2441 * For simplicity, we only consider *pairs* of LINE_UNKNOWNS that are
2442 * known to be identical. If setting them both to YES (or NO) would break
2443 * the clue, set them to NO (or YES). */
2445 for (i
= 0; i
< g
->num_faces
; i
++) {
2446 int N
, yes
, no
, unknown
;
2449 if (sstate
->face_solved
[i
])
2451 clue
= state
->clues
[i
];
2455 N
= g
->faces
[i
].order
;
2456 yes
= sstate
->face_yes_count
[i
];
2457 if (yes
+ 1 == clue
) {
2458 if (face_setall_identical(sstate
, i
, LINE_NO
))
2459 diff
= min(diff
, DIFF_EASY
);
2461 no
= sstate
->face_no_count
[i
];
2462 if (no
+ 1 == N
- clue
) {
2463 if (face_setall_identical(sstate
, i
, LINE_YES
))
2464 diff
= min(diff
, DIFF_EASY
);
2467 /* Reload YES count, it might have changed */
2468 yes
= sstate
->face_yes_count
[i
];
2469 unknown
= N
- no
- yes
;
2471 /* Deductions with small number of LINE_UNKNOWNs, based on overall
2472 * parity of lines. */
2473 diff_tmp
= parity_deductions(sstate
, g
->faces
[i
].edges
,
2474 (clue
- yes
) % 2, unknown
);
2475 diff
= min(diff
, diff_tmp
);
2478 /* ------ Dot deductions ------ */
2479 for (i
= 0; i
< g
->num_dots
; i
++) {
2480 grid_dot
*d
= g
->dots
+ i
;
2483 int yes
, no
, unknown
;
2484 /* Go through dlines, and do any dline<->linedsf deductions wherever
2485 * we find two UNKNOWNS. */
2486 for (j
= 0; j
< N
; j
++) {
2487 int dline_index
= dline_index_from_dot(g
, d
, j
);
2490 int can1
, can2
, inv1
, inv2
;
2492 line1_index
= d
->edges
[j
] - g
->edges
;
2493 if (state
->lines
[line1_index
] != LINE_UNKNOWN
)
2496 if (j2
== N
) j2
= 0;
2497 line2_index
= d
->edges
[j2
] - g
->edges
;
2498 if (state
->lines
[line2_index
] != LINE_UNKNOWN
)
2500 /* Infer dline flags from linedsf */
2501 can1
= edsf_canonify(sstate
->hard
->linedsf
, line1_index
, &inv1
);
2502 can2
= edsf_canonify(sstate
->hard
->linedsf
, line2_index
, &inv2
);
2503 if (can1
== can2
&& inv1
!= inv2
) {
2504 /* These are opposites, so set dline atmostone/atleastone */
2505 if (set_atmostone(dlines
, dline_index
))
2506 diff
= min(diff
, DIFF_NORMAL
);
2507 if (set_atleastone(dlines
, dline_index
))
2508 diff
= min(diff
, DIFF_NORMAL
);
2511 /* Infer linedsf from dline flags */
2512 if (is_atmostone(dlines
, dline_index
)
2513 && is_atleastone(dlines
, dline_index
)) {
2514 if (merge_lines(sstate
, line1_index
, line2_index
, 1))
2515 diff
= min(diff
, DIFF_HARD
);
2519 /* Deductions with small number of LINE_UNKNOWNs, based on overall
2520 * parity of lines. */
2521 yes
= sstate
->dot_yes_count
[i
];
2522 no
= sstate
->dot_no_count
[i
];
2523 unknown
= N
- yes
- no
;
2524 diff_tmp
= parity_deductions(sstate
, d
->edges
,
2526 diff
= min(diff
, diff_tmp
);
2529 /* ------ Edge dsf deductions ------ */
2531 /* If the state of a line is known, deduce the state of its canonical line
2532 * too, and vice versa. */
2533 for (i
= 0; i
< g
->num_edges
; i
++) {
2536 can
= edsf_canonify(sstate
->hard
->linedsf
, i
, &inv
);
2539 s
= sstate
->state
->lines
[can
];
2540 if (s
!= LINE_UNKNOWN
) {
2541 if (solver_set_line(sstate
, i
, inv ?
OPP(s
) : s
))
2542 diff
= min(diff
, DIFF_EASY
);
2544 s
= sstate
->state
->lines
[i
];
2545 if (s
!= LINE_UNKNOWN
) {
2546 if (solver_set_line(sstate
, can
, inv ?
OPP(s
) : s
))
2547 diff
= min(diff
, DIFF_EASY
);
2555 static int loop_deductions(solver_state
*sstate
)
2557 int edgecount
= 0, clues
= 0, satclues
= 0, sm1clues
= 0;
2558 game_state
*state
= sstate
->state
;
2559 grid
*g
= state
->game_grid
;
2560 int shortest_chainlen
= g
->num_dots
;
2561 int loop_found
= FALSE
;
2563 int progress
= FALSE
;
2567 * Go through the grid and update for all the new edges.
2568 * Since merge_dots() is idempotent, the simplest way to
2569 * do this is just to update for _all_ the edges.
2570 * Also, while we're here, we count the edges.
2572 for (i
= 0; i
< g
->num_edges
; i
++) {
2573 if (state
->lines
[i
] == LINE_YES
) {
2574 loop_found
|= merge_dots(sstate
, i
);
2580 * Count the clues, count the satisfied clues, and count the
2581 * satisfied-minus-one clues.
2583 for (i
= 0; i
< g
->num_faces
; i
++) {
2584 int c
= state
->clues
[i
];
2586 int o
= sstate
->face_yes_count
[i
];
2595 for (i
= 0; i
< g
->num_dots
; ++i
) {
2597 sstate
->looplen
[dsf_canonify(sstate
->dotdsf
, i
)];
2598 if (dots_connected
> 1)
2599 shortest_chainlen
= min(shortest_chainlen
, dots_connected
);
2602 assert(sstate
->solver_status
== SOLVER_INCOMPLETE
);
2604 if (satclues
== clues
&& shortest_chainlen
== edgecount
) {
2605 sstate
->solver_status
= SOLVER_SOLVED
;
2606 /* This discovery clearly counts as progress, even if we haven't
2607 * just added any lines or anything */
2609 goto finished_loop_deductionsing
;
2613 * Now go through looking for LINE_UNKNOWN edges which
2614 * connect two dots that are already in the same
2615 * equivalence class. If we find one, test to see if the
2616 * loop it would create is a solution.
2618 for (i
= 0; i
< g
->num_edges
; i
++) {
2619 grid_edge
*e
= g
->edges
+ i
;
2620 int d1
= e
->dot1
- g
->dots
;
2621 int d2
= e
->dot2
- g
->dots
;
2623 if (state
->lines
[i
] != LINE_UNKNOWN
)
2626 eqclass
= dsf_canonify(sstate
->dotdsf
, d1
);
2627 if (eqclass
!= dsf_canonify(sstate
->dotdsf
, d2
))
2630 val
= LINE_NO
; /* loop is bad until proven otherwise */
2633 * This edge would form a loop. Next
2634 * question: how long would the loop be?
2635 * Would it equal the total number of edges
2636 * (plus the one we'd be adding if we added
2639 if (sstate
->looplen
[eqclass
] == edgecount
+ 1) {
2643 * This edge would form a loop which
2644 * took in all the edges in the entire
2645 * grid. So now we need to work out
2646 * whether it would be a valid solution
2647 * to the puzzle, which means we have to
2648 * check if it satisfies all the clues.
2649 * This means that every clue must be
2650 * either satisfied or satisfied-minus-
2651 * 1, and also that the number of
2652 * satisfied-minus-1 clues must be at
2653 * most two and they must lie on either
2654 * side of this edge.
2658 int f
= e
->face1
- g
->faces
;
2659 int c
= state
->clues
[f
];
2660 if (c
>= 0 && sstate
->face_yes_count
[f
] == c
- 1)
2664 int f
= e
->face2
- g
->faces
;
2665 int c
= state
->clues
[f
];
2666 if (c
>= 0 && sstate
->face_yes_count
[f
] == c
- 1)
2669 if (sm1clues
== sm1_nearby
&&
2670 sm1clues
+ satclues
== clues
) {
2671 val
= LINE_YES
; /* loop is good! */
2676 * Right. Now we know that adding this edge
2677 * would form a loop, and we know whether
2678 * that loop would be a viable solution or
2681 * If adding this edge produces a solution,
2682 * then we know we've found _a_ solution but
2683 * we don't know that it's _the_ solution -
2684 * if it were provably the solution then
2685 * we'd have deduced this edge some time ago
2686 * without the need to do loop detection. So
2687 * in this state we return SOLVER_AMBIGUOUS,
2688 * which has the effect that hitting Solve
2689 * on a user-provided puzzle will fill in a
2690 * solution but using the solver to
2691 * construct new puzzles won't consider this
2692 * a reasonable deduction for the user to
2695 progress
= solver_set_line(sstate
, i
, val
);
2696 assert(progress
== TRUE
);
2697 if (val
== LINE_YES
) {
2698 sstate
->solver_status
= SOLVER_AMBIGUOUS
;
2699 goto finished_loop_deductionsing
;
2703 finished_loop_deductionsing
:
2704 return progress ? DIFF_EASY
: DIFF_MAX
;
2707 /* This will return a dynamically allocated solver_state containing the (more)
2709 static solver_state
*solve_game_rec(const solver_state
*sstate_start
,
2712 solver_state
*sstate
, *sstate_saved
;
2713 int solver_progress
;
2716 /* Indicates which solver we should call next. This is a sensible starting
2718 int current_solver
= DIFF_EASY
, next_solver
;
2719 sstate
= dup_solver_state(sstate_start
);
2721 /* Cache the values of some variables for readability */
2722 state
= sstate
->state
;
2724 sstate_saved
= NULL
;
2726 solver_progress
= FALSE
;
2728 check_caches(sstate
);
2731 if (sstate
->solver_status
== SOLVER_MISTAKE
)
2734 next_solver
= solver_fns
[current_solver
](sstate
);
2736 if (next_solver
== DIFF_MAX
) {
2737 if (current_solver
< diff
&& current_solver
+ 1 < DIFF_MAX
) {
2738 /* Try next beefier solver */
2739 next_solver
= current_solver
+ 1;
2741 next_solver
= loop_deductions(sstate
);
2745 if (sstate
->solver_status
== SOLVER_SOLVED
||
2746 sstate
->solver_status
== SOLVER_AMBIGUOUS
) {
2747 /* fprintf(stderr, "Solver completed\n"); */
2751 /* Once we've looped over all permitted solvers then the loop
2752 * deductions without making any progress, we'll exit this while loop */
2753 current_solver
= next_solver
;
2754 } while (current_solver
< DIFF_MAX
);
2756 if (sstate
->solver_status
== SOLVER_SOLVED
||
2757 sstate
->solver_status
== SOLVER_AMBIGUOUS
) {
2758 /* s/LINE_UNKNOWN/LINE_NO/g */
2759 array_setall(sstate
->state
->lines
, LINE_UNKNOWN
, LINE_NO
,
2760 sstate
->state
->game_grid
->num_edges
);
2767 static char *solve_game(game_state
*state
, game_state
*currstate
,
2768 char *aux
, char **error
)
2771 solver_state
*sstate
, *new_sstate
;
2773 sstate
= new_solver_state(state
, DIFF_MAX
);
2774 new_sstate
= solve_game_rec(sstate
, DIFF_MAX
);
2776 if (new_sstate
->solver_status
== SOLVER_SOLVED
) {
2777 soln
= encode_solve_move(new_sstate
->state
);
2778 } else if (new_sstate
->solver_status
== SOLVER_AMBIGUOUS
) {
2779 soln
= encode_solve_move(new_sstate
->state
);
2780 /**error = "Solver found ambiguous solutions"; */
2782 soln
= encode_solve_move(new_sstate
->state
);
2783 /**error = "Solver failed"; */
2786 free_solver_state(new_sstate
);
2787 free_solver_state(sstate
);
2792 /* ----------------------------------------------------------------------
2793 * Drawing and mouse-handling
2796 static char *interpret_move(game_state
*state
, game_ui
*ui
, game_drawstate
*ds
,
2797 int x
, int y
, int button
)
2799 grid
*g
= state
->game_grid
;
2803 char button_char
= ' ';
2804 enum line_state old_state
;
2806 button
&= ~MOD_MASK
;
2808 /* Convert mouse-click (x,y) to grid coordinates */
2809 x
-= BORDER(ds
->tilesize
);
2810 y
-= BORDER(ds
->tilesize
);
2811 x
= x
* g
->tilesize
/ ds
->tilesize
;
2812 y
= y
* g
->tilesize
/ ds
->tilesize
;
2816 e
= grid_nearest_edge(g
, x
, y
);
2822 /* I think it's only possible to play this game with mouse clicks, sorry */
2823 /* Maybe will add mouse drag support some time */
2824 old_state
= state
->lines
[i
];
2828 switch (old_state
) {
2842 switch (old_state
) {
2857 sprintf(buf
, "%d%c", i
, (int)button_char
);
2863 static game_state
*execute_move(game_state
*state
, char *move
)
2866 game_state
*newstate
= dup_game(state
);
2867 grid
*g
= state
->game_grid
;
2869 if (move
[0] == 'S') {
2871 newstate
->cheated
= TRUE
;
2876 move
+= strspn(move
, "1234567890");
2877 switch (*(move
++)) {
2879 newstate
->lines
[i
] = LINE_YES
;
2882 newstate
->lines
[i
] = LINE_NO
;
2885 newstate
->lines
[i
] = LINE_UNKNOWN
;
2893 * Check for completion.
2895 for (i
= 0; i
< g
->num_edges
; i
++) {
2896 if (newstate
->lines
[i
] == LINE_YES
)
2899 if (i
< g
->num_edges
) {
2901 grid_edge
*start_edge
= g
->edges
+ i
;
2902 grid_edge
*e
= start_edge
;
2903 grid_dot
*d
= e
->dot1
;
2905 * We've found an edge i. Follow it round
2906 * to see if it's part of a loop.
2911 int order
= dot_order(newstate
, d
- g
->dots
, LINE_YES
);
2913 goto completion_check_done
;
2915 /* Find other edge around this dot */
2916 for (j
= 0; j
< d
->order
; j
++) {
2917 grid_edge
*e2
= d
->edges
[j
];
2918 if (e2
!= e
&& newstate
->lines
[e2
- g
->edges
] == LINE_YES
)
2921 assert(j
!= d
->order
); /* dot_order guarantees success */
2924 d
= (e
->dot1
== d
) ? e
->dot2
: e
->dot1
;
2927 if (e
== start_edge
)
2932 * We've traced our way round a loop, and we know how many
2933 * line segments were involved. Count _all_ the line
2934 * segments in the grid, to see if the loop includes them
2938 for (i
= 0; i
< g
->num_edges
; i
++) {
2939 if (newstate
->lines
[i
] == LINE_YES
)
2942 assert(count
>= looplen
);
2943 if (count
!= looplen
)
2944 goto completion_check_done
;
2947 * The grid contains one closed loop and nothing else.
2948 * Check that all the clues are satisfied.
2950 for (i
= 0; i
< g
->num_faces
; i
++) {
2951 int c
= newstate
->clues
[i
];
2953 if (face_order(newstate
, i
, LINE_YES
) != c
) {
2954 goto completion_check_done
;
2962 newstate
->solved
= TRUE
;
2965 completion_check_done
:
2969 free_game(newstate
);
2973 /* ----------------------------------------------------------------------
2977 /* Convert from grid coordinates to screen coordinates */
2978 static void grid_to_screen(const game_drawstate
*ds
, const grid
*g
,
2979 int grid_x
, int grid_y
, int *x
, int *y
)
2981 *x
= grid_x
- g
->lowest_x
;
2982 *y
= grid_y
- g
->lowest_y
;
2983 *x
= *x
* ds
->tilesize
/ g
->tilesize
;
2984 *y
= *y
* ds
->tilesize
/ g
->tilesize
;
2985 *x
+= BORDER(ds
->tilesize
);
2986 *y
+= BORDER(ds
->tilesize
);
2989 /* Returns (into x,y) position of centre of face for rendering the text clue.
2991 static void face_text_pos(const game_drawstate
*ds
, const grid
*g
,
2992 const grid_face
*f
, int *x
, int *y
)
2996 /* Simplest solution is the centroid. Might not work in some cases. */
2998 /* Another algorithm to look into:
2999 * Find the midpoints of the sides, find the bounding-box,
3000 * then take the centre of that. */
3002 /* Best solution probably involves incentres (inscribed circles) */
3004 int sx
= 0, sy
= 0; /* sums */
3005 for (i
= 0; i
< f
->order
; i
++) {
3006 grid_dot
*d
= f
->dots
[i
];
3013 /* convert to screen coordinates */
3014 grid_to_screen(ds
, g
, sx
, sy
, x
, y
);
3017 static void game_redraw(drawing
*dr
, game_drawstate
*ds
, game_state
*oldstate
,
3018 game_state
*state
, int dir
, game_ui
*ui
,
3019 float animtime
, float flashtime
)
3021 grid
*g
= state
->game_grid
;
3022 int border
= BORDER(ds
->tilesize
);
3025 int line_colour
, flash_changed
;
3031 * The initial contents of the window are not guaranteed and
3032 * can vary with front ends. To be on the safe side, all games
3033 * should start by drawing a big background-colour rectangle
3034 * covering the whole window.
3036 int grid_width
= g
->highest_x
- g
->lowest_x
;
3037 int grid_height
= g
->highest_y
- g
->lowest_y
;
3038 int w
= grid_width
* ds
->tilesize
/ g
->tilesize
;
3039 int h
= grid_height
* ds
->tilesize
/ g
->tilesize
;
3040 draw_rect(dr
, 0, 0, w
+ 2 * border
, h
+ 2 * border
, COL_BACKGROUND
);
3043 for (i
= 0; i
< g
->num_faces
; i
++) {
3047 c
[0] = CLUE2CHAR(state
->clues
[i
]);
3050 face_text_pos(ds
, g
, f
, &x
, &y
);
3051 draw_text(dr
, x
, y
, FONT_VARIABLE
, ds
->tilesize
/2,
3052 ALIGN_VCENTRE
| ALIGN_HCENTRE
, COL_FOREGROUND
, c
);
3054 draw_update(dr
, 0, 0, w
+ 2 * border
, h
+ 2 * border
);
3057 if (flashtime
> 0 &&
3058 (flashtime
<= FLASH_TIME
/3 ||
3059 flashtime
>= FLASH_TIME
*2/3)) {
3060 flash_changed
= !ds
->flashing
;
3061 ds
->flashing
= TRUE
;
3063 flash_changed
= ds
->flashing
;
3064 ds
->flashing
= FALSE
;
3067 /* Some platforms may perform anti-aliasing, which may prevent clean
3068 * repainting of lines when the colour is changed.
3069 * If a line needs to be over-drawn in a different colour, erase a
3070 * bounding-box around the line, then flag all nearby objects for redraw.
3073 const char redraw_flag
= (char)(1<<7);
3074 for (i
= 0; i
< g
->num_edges
; i
++) {
3075 /* If we're changing state, AND
3076 * the previous state was a coloured line */
3077 if ((state
->lines
[i
] != (ds
->lines
[i
] & ~redraw_flag
)) &&
3078 ((ds
->lines
[i
] & ~redraw_flag
) != LINE_NO
)) {
3079 grid_edge
*e
= g
->edges
+ i
;
3080 int x1
= e
->dot1
->x
;
3081 int y1
= e
->dot1
->y
;
3082 int x2
= e
->dot2
->x
;
3083 int y2
= e
->dot2
->y
;
3084 int xmin
, xmax
, ymin
, ymax
;
3086 grid_to_screen(ds
, g
, x1
, y1
, &x1
, &y1
);
3087 grid_to_screen(ds
, g
, x2
, y2
, &x2
, &y2
);
3088 /* Allow extra margin for dots, and thickness of lines */
3089 xmin
= min(x1
, x2
) - 2;
3090 xmax
= max(x1
, x2
) + 2;
3091 ymin
= min(y1
, y2
) - 2;
3092 ymax
= max(y1
, y2
) + 2;
3093 /* For testing, I find it helpful to change COL_BACKGROUND
3094 * to COL_SATISFIED here. */
3095 draw_rect(dr
, xmin
, ymin
, xmax
- xmin
+ 1, ymax
- ymin
+ 1,
3097 draw_update(dr
, xmin
, ymin
, xmax
- xmin
+ 1, ymax
- ymin
+ 1);
3099 /* Mark nearby lines for redraw */
3100 for (j
= 0; j
< e
->dot1
->order
; j
++)
3101 ds
->lines
[e
->dot1
->edges
[j
] - g
->edges
] |= redraw_flag
;
3102 for (j
= 0; j
< e
->dot2
->order
; j
++)
3103 ds
->lines
[e
->dot2
->edges
[j
] - g
->edges
] |= redraw_flag
;
3104 /* Mark nearby clues for redraw. Use a value that is
3105 * neither TRUE nor FALSE for this. */
3107 ds
->clue_error
[e
->face1
- g
->faces
] = 2;
3109 ds
->clue_error
[e
->face2
- g
->faces
] = 2;
3114 /* Redraw clue colours if necessary */
3115 for (i
= 0; i
< g
->num_faces
; i
++) {
3116 grid_face
*f
= g
->faces
+ i
;
3117 int sides
= f
->order
;
3119 n
= state
->clues
[i
];
3123 c
[0] = CLUE2CHAR(n
);
3126 clue_mistake
= (face_order(state
, i
, LINE_YES
) > n
||
3127 face_order(state
, i
, LINE_NO
) > (sides
-n
));
3129 clue_satisfied
= (face_order(state
, i
, LINE_YES
) == n
&&
3130 face_order(state
, i
, LINE_NO
) == (sides
-n
));
3132 if (clue_mistake
!= ds
->clue_error
[i
]
3133 || clue_satisfied
!= ds
->clue_satisfied
[i
]) {
3135 face_text_pos(ds
, g
, f
, &x
, &y
);
3136 /* There seems to be a certain amount of trial-and-error
3137 * involved in working out the correct bounding-box for
3139 draw_rect(dr
, x
- ds
->tilesize
/4 - 1, y
- ds
->tilesize
/4 - 3,
3140 ds
->tilesize
/2 + 2, ds
->tilesize
/2 + 5,
3143 FONT_VARIABLE
, ds
->tilesize
/2,
3144 ALIGN_VCENTRE
| ALIGN_HCENTRE
,
3145 clue_mistake ? COL_MISTAKE
:
3146 clue_satisfied ? COL_SATISFIED
: COL_FOREGROUND
, c
);
3147 draw_update(dr
, x
- ds
->tilesize
/4 - 1, y
- ds
->tilesize
/4 - 3,
3148 ds
->tilesize
/2 + 2, ds
->tilesize
/2 + 5);
3150 ds
->clue_error
[i
] = clue_mistake
;
3151 ds
->clue_satisfied
[i
] = clue_satisfied
;
3153 /* Sometimes, the bounding-box encroaches into the surrounding
3154 * lines (particularly if the window is resized fairly small).
3155 * So redraw them. */
3156 for (j
= 0; j
< f
->order
; j
++)
3157 ds
->lines
[f
->edges
[j
] - g
->edges
] = -1;
3161 /* I've also had a request to colour lines red if they make a non-solution
3162 * loop, or if more than two lines go into any point. I think that would
3163 * be good some time. */
3166 for (i
= 0; i
< g
->num_edges
; i
++) {
3167 grid_edge
*e
= g
->edges
+ i
;
3169 int xmin
, ymin
, xmax
, ymax
;
3170 int need_draw
= (state
->lines
[i
] != ds
->lines
[i
]) ? TRUE
: FALSE
;
3171 if (flash_changed
&& (state
->lines
[i
] == LINE_YES
))
3174 need_draw
= TRUE
; /* draw everything at the start */
3175 ds
->lines
[i
] = state
->lines
[i
];
3178 if (state
->lines
[i
] == LINE_UNKNOWN
)
3179 line_colour
= COL_LINEUNKNOWN
;
3180 else if (state
->lines
[i
] == LINE_NO
)
3181 line_colour
= COL_BACKGROUND
;
3182 else if (ds
->flashing
)
3183 line_colour
= COL_HIGHLIGHT
;
3185 line_colour
= COL_FOREGROUND
;
3187 /* Convert from grid to screen coordinates */
3188 grid_to_screen(ds
, g
, e
->dot1
->x
, e
->dot1
->y
, &x1
, &y1
);
3189 grid_to_screen(ds
, g
, e
->dot2
->x
, e
->dot2
->y
, &x2
, &y2
);
3196 if (line_colour
!= COL_BACKGROUND
) {
3197 /* (dx, dy) points roughly from (x1, y1) to (x2, y2).
3198 * The line is then "fattened" in a (roughly) perpendicular
3199 * direction to create a thin rectangle. */
3200 int dx
= (x1
> x2
) ?
-1 : ((x1
< x2
) ?
1 : 0);
3201 int dy
= (y1
> y2
) ?
-1 : ((y1
< y2
) ?
1 : 0);
3203 points
[0] = x1
+ dy
;
3204 points
[1] = y1
- dx
;
3205 points
[2] = x1
- dy
;
3206 points
[3] = y1
+ dx
;
3207 points
[4] = x2
- dy
;
3208 points
[5] = y2
+ dx
;
3209 points
[6] = x2
+ dy
;
3210 points
[7] = y2
- dx
;
3211 draw_polygon(dr
, points
, 4, line_colour
, line_colour
);
3214 /* Draw dots at ends of the line */
3215 draw_circle(dr
, x1
, y1
, 2, COL_FOREGROUND
, COL_FOREGROUND
);
3216 draw_circle(dr
, x2
, y2
, 2, COL_FOREGROUND
, COL_FOREGROUND
);
3218 draw_update(dr
, xmin
-2, ymin
-2, xmax
- xmin
+ 4, ymax
- ymin
+ 4);
3223 for (i
= 0; i
< g
->num_dots
; i
++) {
3224 grid_dot
*d
= g
->dots
+ i
;
3226 grid_to_screen(ds
, g
, d
->x
, d
->y
, &x
, &y
);
3227 draw_circle(dr
, x
, y
, 2, COL_FOREGROUND
, COL_FOREGROUND
);
3233 static float game_flash_length(game_state
*oldstate
, game_state
*newstate
,
3234 int dir
, game_ui
*ui
)
3236 if (!oldstate
->solved
&& newstate
->solved
&&
3237 !oldstate
->cheated
&& !newstate
->cheated
) {
3244 static void game_print_size(game_params
*params
, float *x
, float *y
)
3249 * I'll use 7mm "squares" by default.
3251 game_compute_size(params
, 700, &pw
, &ph
);
3256 static void game_print(drawing
*dr
, game_state
*state
, int tilesize
)
3258 int ink
= print_mono_colour(dr
, 0);
3260 game_drawstate ads
, *ds
= &ads
;
3261 grid
*g
= state
->game_grid
;
3263 game_set_size(dr
, ds
, NULL
, tilesize
);
3265 for (i
= 0; i
< g
->num_dots
; i
++) {
3267 grid_to_screen(ds
, g
, g
->dots
[i
].x
, g
->dots
[i
].y
, &x
, &y
);
3268 draw_circle(dr
, x
, y
, ds
->tilesize
/ 15, ink
, ink
);
3274 for (i
= 0; i
< g
->num_faces
; i
++) {
3275 grid_face
*f
= g
->faces
+ i
;
3276 int clue
= state
->clues
[i
];
3280 c
[0] = CLUE2CHAR(clue
);
3282 face_text_pos(ds
, g
, f
, &x
, &y
);
3284 FONT_VARIABLE
, ds
->tilesize
/ 2,
3285 ALIGN_VCENTRE
| ALIGN_HCENTRE
, ink
, c
);
3292 for (i
= 0; i
< g
->num_edges
; i
++) {
3293 int thickness
= (state
->lines
[i
] == LINE_YES
) ?
30 : 150;
3294 grid_edge
*e
= g
->edges
+ i
;
3296 grid_to_screen(ds
, g
, e
->dot1
->x
, e
->dot1
->y
, &x1
, &y1
);
3297 grid_to_screen(ds
, g
, e
->dot2
->x
, e
->dot2
->y
, &x2
, &y2
);
3298 if (state
->lines
[i
] == LINE_YES
)
3300 /* (dx, dy) points from (x1, y1) to (x2, y2).
3301 * The line is then "fattened" in a perpendicular
3302 * direction to create a thin rectangle. */
3303 double d
= sqrt(SQ((double)x1
- x2
) + SQ((double)y1
- y2
));
3304 double dx
= (x2
- x1
) / d
;
3305 double dy
= (y2
- y1
) / d
;
3308 dx
= (dx
* ds
->tilesize
) / thickness
;
3309 dy
= (dy
* ds
->tilesize
) / thickness
;
3310 points
[0] = x1
+ (int)dy
;
3311 points
[1] = y1
- (int)dx
;
3312 points
[2] = x1
- (int)dy
;
3313 points
[3] = y1
+ (int)dx
;
3314 points
[4] = x2
- (int)dy
;
3315 points
[5] = y2
+ (int)dx
;
3316 points
[6] = x2
+ (int)dy
;
3317 points
[7] = y2
- (int)dx
;
3318 draw_polygon(dr
, points
, 4, ink
, ink
);
3322 /* Draw a dotted line */
3325 for (j
= 1; j
< divisions
; j
++) {
3326 /* Weighted average */
3327 int x
= (x1
* (divisions
-j
) + x2
* j
) / divisions
;
3328 int y
= (y1
* (divisions
-j
) + y2
* j
) / divisions
;
3329 draw_circle(dr
, x
, y
, ds
->tilesize
/ thickness
, ink
, ink
);
3336 #define thegame loopy
3339 const struct game thegame
= {
3340 "Loopy", "games.loopy", "loopy",
3347 TRUE
, game_configure
, custom_params
,
3355 TRUE
, game_can_format_as_text_now
, game_text_format
,
3363 PREFERRED_TILE_SIZE
, game_compute_size
, game_set_size
,
3366 game_free_drawstate
,
3370 TRUE
, FALSE
, game_print_size
, game_print
,
3371 FALSE
/* wants_statusbar */,
3372 FALSE
, game_timing_state
,
3373 0, /* mouse_priorities */