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 static const int 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
[] = {
467 { 7, 7, DIFF_EASY
, 0, NULL
},
468 { 10, 10, DIFF_EASY
, 0, NULL
},
469 { 7, 7, DIFF_NORMAL
, 0, NULL
},
470 { 10, 10, DIFF_NORMAL
, 0, NULL
},
471 { 7, 7, DIFF_HARD
, 0, NULL
},
472 { 10, 10, DIFF_HARD
, 0, NULL
},
473 { 10, 10, DIFF_HARD
, 1, NULL
},
474 { 12, 10, DIFF_HARD
, 2, NULL
},
475 { 7, 7, DIFF_HARD
, 3, NULL
},
476 { 9, 9, DIFF_HARD
, 4, NULL
},
477 { 5, 4, DIFF_HARD
, 5, NULL
},
478 { 7, 7, DIFF_HARD
, 6, NULL
},
479 { 5, 5, DIFF_HARD
, 7, NULL
},
482 static int game_fetch_preset(int i
, char **name
, game_params
**params
)
487 if (i
< 0 || i
>= lenof(presets
))
490 tmppar
= snew(game_params
);
491 *tmppar
= presets
[i
];
493 sprintf(buf
, "%dx%d %s - %s", tmppar
->h
, tmppar
->w
,
494 gridnames
[tmppar
->type
], diffnames
[tmppar
->diff
]);
500 static void free_params(game_params
*params
)
502 if (params
->game_grid
) {
503 grid_free(params
->game_grid
);
508 static void decode_params(game_params
*params
, char const *string
)
510 if (params
->game_grid
) {
511 grid_free(params
->game_grid
);
512 params
->game_grid
= NULL
;
514 params
->h
= params
->w
= atoi(string
);
515 params
->diff
= DIFF_EASY
;
516 while (*string
&& isdigit((unsigned char)*string
)) string
++;
517 if (*string
== 'x') {
519 params
->h
= atoi(string
);
520 while (*string
&& isdigit((unsigned char)*string
)) string
++;
522 if (*string
== 't') {
524 params
->type
= atoi(string
);
525 while (*string
&& isdigit((unsigned char)*string
)) string
++;
527 if (*string
== 'd') {
530 for (i
= 0; i
< DIFF_MAX
; i
++)
531 if (*string
== diffchars
[i
])
533 if (*string
) string
++;
537 static char *encode_params(game_params
*params
, int full
)
540 sprintf(str
, "%dx%dt%d", params
->w
, params
->h
, params
->type
);
542 sprintf(str
+ strlen(str
), "d%c", diffchars
[params
->diff
]);
546 static config_item
*game_configure(game_params
*params
)
551 ret
= snewn(5, config_item
);
553 ret
[0].name
= "Width";
554 ret
[0].type
= C_STRING
;
555 sprintf(buf
, "%d", params
->w
);
556 ret
[0].sval
= dupstr(buf
);
559 ret
[1].name
= "Height";
560 ret
[1].type
= C_STRING
;
561 sprintf(buf
, "%d", params
->h
);
562 ret
[1].sval
= dupstr(buf
);
565 ret
[2].name
= "Grid type";
566 ret
[2].type
= C_CHOICES
;
567 ret
[2].sval
= GRID_CONFIGS
;
568 ret
[2].ival
= params
->type
;
570 ret
[3].name
= "Difficulty";
571 ret
[3].type
= C_CHOICES
;
572 ret
[3].sval
= DIFFCONFIG
;
573 ret
[3].ival
= params
->diff
;
583 static game_params
*custom_params(config_item
*cfg
)
585 game_params
*ret
= snew(game_params
);
587 ret
->w
= atoi(cfg
[0].sval
);
588 ret
->h
= atoi(cfg
[1].sval
);
589 ret
->type
= cfg
[2].ival
;
590 ret
->diff
= cfg
[3].ival
;
592 ret
->game_grid
= NULL
;
596 static char *validate_params(game_params
*params
, int full
)
598 if (params
->w
< 3 || params
->h
< 3)
599 return "Width and height must both be at least 3";
600 if (params
->type
< 0 || params
->type
>= NUM_GRID_TYPES
)
601 return "Illegal grid type";
604 * This shouldn't be able to happen at all, since decode_params
605 * and custom_params will never generate anything that isn't
608 assert(params
->diff
< DIFF_MAX
);
613 /* Returns a newly allocated string describing the current puzzle */
614 static char *state_to_text(const game_state
*state
)
616 grid
*g
= state
->game_grid
;
618 int num_faces
= g
->num_faces
;
619 char *description
= snewn(num_faces
+ 1, char);
620 char *dp
= description
;
624 for (i
= 0; i
< num_faces
; i
++) {
625 if (state
->clues
[i
] < 0) {
626 if (empty_count
> 25) {
627 dp
+= sprintf(dp
, "%c", (int)(empty_count
+ 'a' - 1));
633 dp
+= sprintf(dp
, "%c", (int)(empty_count
+ 'a' - 1));
636 dp
+= sprintf(dp
, "%c", (int)CLUE2CHAR(state
->clues
[i
]));
641 dp
+= sprintf(dp
, "%c", (int)(empty_count
+ 'a' - 1));
643 retval
= dupstr(description
);
649 /* We require that the params pass the test in validate_params and that the
650 * description fills the entire game area */
651 static char *validate_desc(game_params
*params
, char *desc
)
655 params_generate_grid(params
);
656 g
= params
->game_grid
;
658 for (; *desc
; ++desc
) {
659 if (*desc
>= '0' && *desc
<= '9') {
664 count
+= *desc
- 'a' + 1;
667 return "Unknown character in description";
670 if (count
< g
->num_faces
)
671 return "Description too short for board size";
672 if (count
> g
->num_faces
)
673 return "Description too long for board size";
678 /* Sums the lengths of the numbers in range [0,n) */
679 /* See equivalent function in solo.c for justification of this. */
680 static int len_0_to_n(int n
)
682 int len
= 1; /* Counting 0 as a bit of a special case */
685 for (i
= 1; i
< n
; i
*= 10) {
686 len
+= max(n
- i
, 0);
692 static char *encode_solve_move(const game_state
*state
)
697 int num_edges
= state
->game_grid
->num_edges
;
699 /* This is going to return a string representing the moves needed to set
700 * every line in a grid to be the same as the ones in 'state'. The exact
701 * length of this string is predictable. */
703 len
= 1; /* Count the 'S' prefix */
704 /* Numbers in all lines */
705 len
+= len_0_to_n(num_edges
);
706 /* For each line we also have a letter */
709 ret
= snewn(len
+ 1, char);
712 p
+= sprintf(p
, "S");
714 for (i
= 0; i
< num_edges
; i
++) {
715 switch (state
->lines
[i
]) {
717 p
+= sprintf(p
, "%dy", i
);
720 p
+= sprintf(p
, "%dn", i
);
725 /* No point in doing sums like that if they're going to be wrong */
726 assert(strlen(ret
) <= (size_t)len
);
730 static game_ui
*new_ui(game_state
*state
)
735 static void free_ui(game_ui
*ui
)
739 static char *encode_ui(game_ui
*ui
)
744 static void decode_ui(game_ui
*ui
, char *encoding
)
748 static void game_changed_state(game_ui
*ui
, game_state
*oldstate
,
749 game_state
*newstate
)
753 static void game_compute_size(game_params
*params
, int tilesize
,
757 int grid_width
, grid_height
, rendered_width
, rendered_height
;
759 params_generate_grid(params
);
760 g
= params
->game_grid
;
761 grid_width
= g
->highest_x
- g
->lowest_x
;
762 grid_height
= g
->highest_y
- g
->lowest_y
;
763 /* multiply first to minimise rounding error on integer division */
764 rendered_width
= grid_width
* tilesize
/ g
->tilesize
;
765 rendered_height
= grid_height
* tilesize
/ g
->tilesize
;
766 *x
= rendered_width
+ 2 * BORDER(tilesize
) + 1;
767 *y
= rendered_height
+ 2 * BORDER(tilesize
) + 1;
770 static void game_set_size(drawing
*dr
, game_drawstate
*ds
,
771 game_params
*params
, int tilesize
)
773 ds
->tilesize
= tilesize
;
776 static float *game_colours(frontend
*fe
, int *ncolours
)
778 float *ret
= snewn(4 * NCOLOURS
, float);
780 frontend_default_colour(fe
, &ret
[COL_BACKGROUND
* 3]);
782 ret
[COL_FOREGROUND
* 3 + 0] = 0.0F
;
783 ret
[COL_FOREGROUND
* 3 + 1] = 0.0F
;
784 ret
[COL_FOREGROUND
* 3 + 2] = 0.0F
;
786 ret
[COL_LINEUNKNOWN
* 3 + 0] = 0.8F
;
787 ret
[COL_LINEUNKNOWN
* 3 + 1] = 0.8F
;
788 ret
[COL_LINEUNKNOWN
* 3 + 2] = 0.0F
;
790 ret
[COL_HIGHLIGHT
* 3 + 0] = 1.0F
;
791 ret
[COL_HIGHLIGHT
* 3 + 1] = 1.0F
;
792 ret
[COL_HIGHLIGHT
* 3 + 2] = 1.0F
;
794 ret
[COL_MISTAKE
* 3 + 0] = 1.0F
;
795 ret
[COL_MISTAKE
* 3 + 1] = 0.0F
;
796 ret
[COL_MISTAKE
* 3 + 2] = 0.0F
;
798 ret
[COL_SATISFIED
* 3 + 0] = 0.0F
;
799 ret
[COL_SATISFIED
* 3 + 1] = 0.0F
;
800 ret
[COL_SATISFIED
* 3 + 2] = 0.0F
;
802 *ncolours
= NCOLOURS
;
806 static game_drawstate
*game_new_drawstate(drawing
*dr
, game_state
*state
)
808 struct game_drawstate
*ds
= snew(struct game_drawstate
);
809 int num_faces
= state
->game_grid
->num_faces
;
810 int num_edges
= state
->game_grid
->num_edges
;
814 ds
->lines
= snewn(num_edges
, char);
815 ds
->clue_error
= snewn(num_faces
, char);
816 ds
->clue_satisfied
= snewn(num_faces
, char);
819 memset(ds
->lines
, LINE_UNKNOWN
, num_edges
);
820 memset(ds
->clue_error
, 0, num_faces
);
821 memset(ds
->clue_satisfied
, 0, num_faces
);
826 static void game_free_drawstate(drawing
*dr
, game_drawstate
*ds
)
828 sfree(ds
->clue_error
);
829 sfree(ds
->clue_satisfied
);
834 static int game_timing_state(game_state
*state
, game_ui
*ui
)
839 static float game_anim_length(game_state
*oldstate
, game_state
*newstate
,
840 int dir
, game_ui
*ui
)
845 static int game_can_format_as_text_now(game_params
*params
)
847 if (params
->type
!= 0)
852 static char *game_text_format(game_state
*state
)
858 grid
*g
= state
->game_grid
;
861 assert(state
->grid_type
== 0);
863 /* Work out the basic size unit */
864 f
= g
->faces
; /* first face */
865 assert(f
->order
== 4);
866 /* The dots are ordered clockwise, so the two opposite
867 * corners are guaranteed to span the square */
868 cell_size
= abs(f
->dots
[0]->x
- f
->dots
[2]->x
);
870 w
= (g
->highest_x
- g
->lowest_x
) / cell_size
;
871 h
= (g
->highest_y
- g
->lowest_y
) / cell_size
;
873 /* Create a blank "canvas" to "draw" on */
876 ret
= snewn(W
* H
+ 1, char);
877 for (y
= 0; y
< H
; y
++) {
878 for (x
= 0; x
< W
-1; x
++) {
881 ret
[y
*W
+ W
-1] = '\n';
885 /* Fill in edge info */
886 for (i
= 0; i
< g
->num_edges
; i
++) {
887 grid_edge
*e
= g
->edges
+ i
;
888 /* Cell coordinates, from (0,0) to (w-1,h-1) */
889 int x1
= (e
->dot1
->x
- g
->lowest_x
) / cell_size
;
890 int x2
= (e
->dot2
->x
- g
->lowest_x
) / cell_size
;
891 int y1
= (e
->dot1
->y
- g
->lowest_y
) / cell_size
;
892 int y2
= (e
->dot2
->y
- g
->lowest_y
) / cell_size
;
893 /* Midpoint, in canvas coordinates (canvas coordinates are just twice
894 * cell coordinates) */
897 switch (state
->lines
[i
]) {
899 ret
[y
*W
+ x
] = (y1
== y2
) ?
'-' : '|';
905 break; /* already a space */
907 assert(!"Illegal line state");
912 for (i
= 0; i
< g
->num_faces
; i
++) {
916 assert(f
->order
== 4);
917 /* Cell coordinates, from (0,0) to (w-1,h-1) */
918 x1
= (f
->dots
[0]->x
- g
->lowest_x
) / cell_size
;
919 x2
= (f
->dots
[2]->x
- g
->lowest_x
) / cell_size
;
920 y1
= (f
->dots
[0]->y
- g
->lowest_y
) / cell_size
;
921 y2
= (f
->dots
[2]->y
- g
->lowest_y
) / cell_size
;
922 /* Midpoint, in canvas coordinates */
925 ret
[y
*W
+ x
] = CLUE2CHAR(state
->clues
[i
]);
930 /* ----------------------------------------------------------------------
935 static void check_caches(const solver_state
* sstate
)
938 const game_state
*state
= sstate
->state
;
939 const grid
*g
= state
->game_grid
;
941 for (i
= 0; i
< g
->num_dots
; i
++) {
942 assert(dot_order(state
, i
, LINE_YES
) == sstate
->dot_yes_count
[i
]);
943 assert(dot_order(state
, i
, LINE_NO
) == sstate
->dot_no_count
[i
]);
946 for (i
= 0; i
< g
->num_faces
; i
++) {
947 assert(face_order(state
, i
, LINE_YES
) == sstate
->face_yes_count
[i
]);
948 assert(face_order(state
, i
, LINE_NO
) == sstate
->face_no_count
[i
]);
953 #define check_caches(s) \
955 fprintf(stderr, "check_caches at line %d\n", __LINE__); \
959 #endif /* DEBUG_CACHES */
961 /* ----------------------------------------------------------------------
962 * Solver utility functions
965 /* Sets the line (with index i) to the new state 'line_new', and updates
966 * the cached counts of any affected faces and dots.
967 * Returns TRUE if this actually changed the line's state. */
968 static int solver_set_line(solver_state
*sstate
, int i
,
969 enum line_state line_new
975 game_state
*state
= sstate
->state
;
979 assert(line_new
!= LINE_UNKNOWN
);
981 check_caches(sstate
);
983 if (state
->lines
[i
] == line_new
) {
984 return FALSE
; /* nothing changed */
986 state
->lines
[i
] = line_new
;
989 fprintf(stderr
, "solver: set line [%d] to %s (%s)\n",
990 i
, line_new
== LINE_YES ?
"YES" : "NO",
994 g
= state
->game_grid
;
997 /* Update the cache for both dots and both faces affected by this. */
998 if (line_new
== LINE_YES
) {
999 sstate
->dot_yes_count
[e
->dot1
- g
->dots
]++;
1000 sstate
->dot_yes_count
[e
->dot2
- g
->dots
]++;
1002 sstate
->face_yes_count
[e
->face1
- g
->faces
]++;
1005 sstate
->face_yes_count
[e
->face2
- g
->faces
]++;
1008 sstate
->dot_no_count
[e
->dot1
- g
->dots
]++;
1009 sstate
->dot_no_count
[e
->dot2
- g
->dots
]++;
1011 sstate
->face_no_count
[e
->face1
- g
->faces
]++;
1014 sstate
->face_no_count
[e
->face2
- g
->faces
]++;
1018 check_caches(sstate
);
1023 #define solver_set_line(a, b, c) \
1024 solver_set_line(a, b, c, __FUNCTION__)
1028 * Merge two dots due to the existence of an edge between them.
1029 * Updates the dsf tracking equivalence classes, and keeps track of
1030 * the length of path each dot is currently a part of.
1031 * Returns TRUE if the dots were already linked, ie if they are part of a
1032 * closed loop, and false otherwise.
1034 static int merge_dots(solver_state
*sstate
, int edge_index
)
1037 grid
*g
= sstate
->state
->game_grid
;
1038 grid_edge
*e
= g
->edges
+ edge_index
;
1040 i
= e
->dot1
- g
->dots
;
1041 j
= e
->dot2
- g
->dots
;
1043 i
= dsf_canonify(sstate
->dotdsf
, i
);
1044 j
= dsf_canonify(sstate
->dotdsf
, j
);
1049 len
= sstate
->looplen
[i
] + sstate
->looplen
[j
];
1050 dsf_merge(sstate
->dotdsf
, i
, j
);
1051 i
= dsf_canonify(sstate
->dotdsf
, i
);
1052 sstate
->looplen
[i
] = len
;
1057 /* Merge two lines because the solver has deduced that they must be either
1058 * identical or opposite. Returns TRUE if this is new information, otherwise
1060 static int merge_lines(solver_state
*sstate
, int i
, int j
, int inverse
1062 , const char *reason
1068 assert(i
< sstate
->state
->game_grid
->num_edges
);
1069 assert(j
< sstate
->state
->game_grid
->num_edges
);
1071 i
= edsf_canonify(sstate
->hard
->linedsf
, i
, &inv_tmp
);
1073 j
= edsf_canonify(sstate
->hard
->linedsf
, j
, &inv_tmp
);
1076 edsf_merge(sstate
->hard
->linedsf
, i
, j
, inverse
);
1080 fprintf(stderr
, "%s [%d] [%d] %s(%s)\n",
1082 inverse ?
"inverse " : "", reason
);
1089 #define merge_lines(a, b, c, d) \
1090 merge_lines(a, b, c, d, __FUNCTION__)
1093 /* Count the number of lines of a particular type currently going into the
1095 static int dot_order(const game_state
* state
, int dot
, char line_type
)
1098 grid
*g
= state
->game_grid
;
1099 grid_dot
*d
= g
->dots
+ dot
;
1102 for (i
= 0; i
< d
->order
; i
++) {
1103 grid_edge
*e
= d
->edges
[i
];
1104 if (state
->lines
[e
- g
->edges
] == line_type
)
1110 /* Count the number of lines of a particular type currently surrounding the
1112 static int face_order(const game_state
* state
, int face
, char line_type
)
1115 grid
*g
= state
->game_grid
;
1116 grid_face
*f
= g
->faces
+ face
;
1119 for (i
= 0; i
< f
->order
; i
++) {
1120 grid_edge
*e
= f
->edges
[i
];
1121 if (state
->lines
[e
- g
->edges
] == line_type
)
1127 /* Set all lines bordering a dot of type old_type to type new_type
1128 * Return value tells caller whether this function actually did anything */
1129 static int dot_setall(solver_state
*sstate
, int dot
,
1130 char old_type
, char new_type
)
1132 int retval
= FALSE
, r
;
1133 game_state
*state
= sstate
->state
;
1138 if (old_type
== new_type
)
1141 g
= state
->game_grid
;
1144 for (i
= 0; i
< d
->order
; i
++) {
1145 int line_index
= d
->edges
[i
] - g
->edges
;
1146 if (state
->lines
[line_index
] == old_type
) {
1147 r
= solver_set_line(sstate
, line_index
, new_type
);
1155 /* Set all lines bordering a face of type old_type to type new_type */
1156 static int face_setall(solver_state
*sstate
, int face
,
1157 char old_type
, char new_type
)
1159 int retval
= FALSE
, r
;
1160 game_state
*state
= sstate
->state
;
1165 if (old_type
== new_type
)
1168 g
= state
->game_grid
;
1169 f
= g
->faces
+ face
;
1171 for (i
= 0; i
< f
->order
; i
++) {
1172 int line_index
= f
->edges
[i
] - g
->edges
;
1173 if (state
->lines
[line_index
] == old_type
) {
1174 r
= solver_set_line(sstate
, line_index
, new_type
);
1182 /* ----------------------------------------------------------------------
1183 * Loop generation and clue removal
1186 /* We're going to store a list of current candidate faces for lighting.
1187 * Each face gets a 'score', which tells us how adding that face right
1188 * now would affect the length of the solution loop. We're trying to
1189 * maximise that quantity so will bias our random selection of faces to
1190 * light towards those with high scores */
1193 unsigned long random
;
1197 static int get_face_cmpfn(void *v1
, void *v2
)
1199 struct face
*f1
= v1
;
1200 struct face
*f2
= v2
;
1201 /* These grid_face pointers always point into the same list of
1202 * 'grid_face's, so it's valid to subtract them. */
1203 return f1
->f
- f2
->f
;
1206 static int face_sort_cmpfn(void *v1
, void *v2
)
1208 struct face
*f1
= v1
;
1209 struct face
*f2
= v2
;
1212 r
= f2
->score
- f1
->score
;
1217 if (f1
->random
< f2
->random
)
1219 else if (f1
->random
> f2
->random
)
1223 * It's _just_ possible that two faces might have been given
1224 * the same random value. In that situation, fall back to
1225 * comparing based on the positions within the grid's face-list.
1226 * This introduces a tiny directional bias, but not a significant one.
1228 return get_face_cmpfn(f1
, f2
);
1231 enum { FACE_LIT
, FACE_UNLIT
};
1233 /* face should be of type grid_face* here. */
1234 #define FACE_LIT_STATE(face) \
1235 ( (face) == NULL ? FACE_UNLIT : \
1236 board[(face) - g->faces] )
1238 /* 'board' is an array of these enums, indicating which faces are
1239 * currently lit. Returns whether it's legal to light up the
1241 static int can_light_face(grid
*g
, char* board
, int face_index
)
1244 grid_face
*test_face
= g
->faces
+ face_index
;
1245 grid_face
*starting_face
, *current_face
;
1247 int current_state
, s
;
1248 int found_lit_neighbour
= FALSE
;
1249 assert(board
[face_index
] == FACE_UNLIT
);
1251 /* Can only consider a face for lighting if it's adjacent to an
1252 * already lit face. */
1253 for (i
= 0; i
< test_face
->order
; i
++) {
1254 grid_edge
*e
= test_face
->edges
[i
];
1255 grid_face
*f
= (e
->face1
== test_face
) ? e
->face2
: e
->face1
;
1256 if (FACE_LIT_STATE(f
) == FACE_LIT
) {
1257 found_lit_neighbour
= TRUE
;
1261 if (!found_lit_neighbour
)
1264 /* Need to avoid creating a loop of lit faces around some unlit faces.
1265 * Also need to avoid meeting another lit face at a corner, with
1266 * unlit faces in between. Here's a simple test that (I believe) takes
1267 * care of both these conditions:
1269 * Take the circular path formed by this face's edges, and inflate it
1270 * slightly outwards. Imagine walking around this path and consider
1271 * the faces that you visit in sequence. This will include all faces
1272 * touching the given face, either along an edge or just at a corner.
1273 * Count the number of LIT/UNLIT transitions you encounter, as you walk
1274 * along the complete loop. This will obviously turn out to be an even
1276 * If 0, we're either in a completely unlit zone, or this face is a hole
1277 * in a completely lit zone. If the former, we would create a brand new
1278 * island by lighting this face. And the latter ought to be impossible -
1279 * it would mean there's already a lit loop, so something went wrong
1281 * If 4 or greater, there are too many separate lit regions touching this
1282 * face, and lighting it up would create a loop or a corner-violation.
1283 * The only allowed case is when the count is exactly 2. */
1285 /* i points to a dot around the test face.
1286 * j points to a face around the i^th dot.
1287 * The current face will always be:
1288 * test_face->dots[i]->faces[j]
1289 * We assume dots go clockwise around the test face,
1290 * and faces go clockwise around dots. */
1292 starting_face
= test_face
->dots
[0]->faces
[0];
1293 if (starting_face
== test_face
) {
1295 starting_face
= test_face
->dots
[0]->faces
[1];
1297 current_face
= starting_face
;
1299 current_state
= FACE_LIT_STATE(current_face
);
1302 /* Advance to next face.
1303 * Need to loop here because it might take several goes to
1307 if (j
== test_face
->dots
[i
]->order
)
1310 if (test_face
->dots
[i
]->faces
[j
] == test_face
) {
1311 /* Advance to next dot round test_face, then
1312 * find current_face around new dot
1313 * and advance to the next face clockwise */
1315 if (i
== test_face
->order
)
1317 for (j
= 0; j
< test_face
->dots
[i
]->order
; j
++) {
1318 if (test_face
->dots
[i
]->faces
[j
] == current_face
)
1321 /* Must actually find current_face around new dot,
1322 * or else something's wrong with the grid. */
1323 assert(j
!= test_face
->dots
[i
]->order
);
1324 /* Found, so advance to next face and try again */
1329 /* (i,j) are now advanced to next face */
1330 current_face
= test_face
->dots
[i
]->faces
[j
];
1331 s
= FACE_LIT_STATE(current_face
);
1332 if (s
!= current_state
) {
1335 if (transitions
> 2)
1336 return FALSE
; /* no point in continuing */
1338 } while (current_face
!= starting_face
);
1340 return (transitions
== 2) ? TRUE
: FALSE
;
1343 /* The 'score' of a face reflects its current desirability for selection
1344 * as the next face to light. We want to encourage moving into uncharted
1345 * areas so we give scores according to how many of the face's neighbours
1346 * are currently unlit. */
1347 static int face_score(grid
*g
, char *board
, grid_face
*face
)
1349 /* Simple formula: score = neighbours unlit - neighbours lit */
1350 int lit_count
= 0, unlit_count
= 0;
1354 for (i
= 0; i
< face
->order
; i
++) {
1356 f
= (e
->face1
== face
) ? e
->face2
: e
->face1
;
1357 if (FACE_LIT_STATE(f
) == FACE_LIT
)
1362 return unlit_count
- lit_count
;
1365 /* Generate a new complete set of clues for the given game_state. */
1366 static void add_full_clues(game_state
*state
, random_state
*rs
)
1368 signed char *clues
= state
->clues
;
1370 grid
*g
= state
->game_grid
;
1372 int num_faces
= g
->num_faces
;
1373 int first_time
= TRUE
;
1375 struct face
*face
, *tmpface
;
1376 struct face face_pos
;
1378 /* These will contain exactly the same information, sorted into different
1380 tree234
*lightable_faces_sorted
, *lightable_faces_gettable
;
1382 #define IS_LIGHTING_CANDIDATE(i) \
1383 (board[i] == FACE_UNLIT && \
1384 can_light_face(g, board, i))
1386 board
= snewn(num_faces
, char);
1389 memset(board
, FACE_UNLIT
, num_faces
);
1391 /* We need a way of favouring faces that will increase our loopiness.
1392 * We do this by maintaining a list of all candidate faces sorted by
1393 * their score and choose randomly from that with appropriate skew.
1394 * In order to avoid consistently biasing towards particular faces, we
1395 * need the sort order _within_ each group of scores to be completely
1396 * random. But it would be abusing the hospitality of the tree234 data
1397 * structure if our comparison function were nondeterministic :-). So with
1398 * each face we associate a random number that does not change during a
1399 * particular run of the generator, and use that as a secondary sort key.
1400 * Yes, this means we will be biased towards particular random faces in
1401 * any one run but that doesn't actually matter. */
1403 lightable_faces_sorted
= newtree234(face_sort_cmpfn
);
1404 lightable_faces_gettable
= newtree234(get_face_cmpfn
);
1405 #define ADD_FACE(f) \
1407 struct face *x = add234(lightable_faces_sorted, f); \
1409 x = add234(lightable_faces_gettable, f); \
1413 #define REMOVE_FACE(f) \
1415 struct face *x = del234(lightable_faces_sorted, f); \
1417 x = del234(lightable_faces_gettable, f); \
1421 /* Light faces one at a time until the board is interesting enough */
1426 /* lightable_faces_xxx are empty, so start the process by
1427 * lighting up the middle face. These tree234s should
1428 * remain empty, consistent with what would happen if
1429 * first_time were FALSE. */
1430 board
[g
->middle_face
- g
->faces
] = FACE_LIT
;
1431 face
= snew(struct face
);
1432 face
->f
= g
->middle_face
;
1433 /* No need to initialise any more of 'face' here, no other fields
1434 * are used in this case. */
1436 /* We have count234(lightable_faces_gettable) possibilities, and in
1437 * lightable_faces_sorted they are sorted with the most desirable
1439 c
= count234(lightable_faces_sorted
);
1442 assert(c
== count234(lightable_faces_gettable
));
1444 /* Check that the best face available is any good */
1445 face
= (struct face
*)index234(lightable_faces_sorted
, 0);
1449 * The situation for a general grid is slightly different from
1450 * a square grid. Decreasing the perimeter should be allowed
1451 * sometimes (think about creating a hexagon of lit triangles,
1452 * for example). For if it were _never_ done, then the user would
1453 * be able to illicitly deduce certain things. So we do it
1454 * sometimes but not always.
1456 if (face
->score
<= 0 && random_upto(rs
, 2) == 0) {
1460 assert(face
->f
); /* not the infinite face */
1461 assert(FACE_LIT_STATE(face
->f
) == FACE_UNLIT
);
1463 /* Update data structures */
1464 /* Light up the face and remove it from the lists */
1465 board
[face
->f
- g
->faces
] = FACE_LIT
;
1469 /* The face we've just lit up potentially affects the lightability
1470 * of any neighbouring faces (touching at a corner or edge). So the
1471 * search needs to be conducted around all faces touching the one
1472 * we've just lit. Iterate over its corners, then over each corner's
1474 for (i
= 0; i
< face
->f
->order
; i
++) {
1475 grid_dot
*d
= face
->f
->dots
[i
];
1476 for (j
= 0; j
< d
->order
; j
++) {
1477 grid_face
*f2
= d
->faces
[j
];
1483 tmpface
= find234(lightable_faces_gettable
, &face_pos
, NULL
);
1485 assert(tmpface
->f
== face_pos
.f
);
1486 assert(FACE_LIT_STATE(tmpface
->f
) == FACE_UNLIT
);
1487 REMOVE_FACE(tmpface
);
1489 tmpface
= snew(struct face
);
1490 tmpface
->f
= face_pos
.f
;
1491 tmpface
->random
= random_bits(rs
, 31);
1493 tmpface
->score
= face_score(g
, board
, tmpface
->f
);
1495 if (IS_LIGHTING_CANDIDATE(tmpface
->f
- g
->faces
)) {
1506 while ((face
= delpos234(lightable_faces_gettable
, 0)) != NULL
)
1508 freetree234(lightable_faces_gettable
);
1509 freetree234(lightable_faces_sorted
);
1511 /* Fill out all the clues by initialising to 0, then iterating over
1512 * all edges and incrementing each clue as we find edges that border
1513 * between LIT/UNLIT faces */
1514 memset(clues
, 0, num_faces
);
1515 for (i
= 0; i
< g
->num_edges
; i
++) {
1516 grid_edge
*e
= g
->edges
+ i
;
1517 grid_face
*f1
= e
->face1
;
1518 grid_face
*f2
= e
->face2
;
1519 if (FACE_LIT_STATE(f1
) != FACE_LIT_STATE(f2
)) {
1520 if (f1
) clues
[f1
- g
->faces
]++;
1521 if (f2
) clues
[f2
- g
->faces
]++;
1529 static int game_has_unique_soln(const game_state
*state
, int diff
)
1532 solver_state
*sstate_new
;
1533 solver_state
*sstate
= new_solver_state((game_state
*)state
, diff
);
1535 sstate_new
= solve_game_rec(sstate
, diff
);
1537 assert(sstate_new
->solver_status
!= SOLVER_MISTAKE
);
1538 ret
= (sstate_new
->solver_status
== SOLVER_SOLVED
);
1540 free_solver_state(sstate_new
);
1541 free_solver_state(sstate
);
1547 /* Remove clues one at a time at random. */
1548 static game_state
*remove_clues(game_state
*state
, random_state
*rs
,
1552 int num_faces
= state
->game_grid
->num_faces
;
1553 game_state
*ret
= dup_game(state
), *saved_ret
;
1556 /* We need to remove some clues. We'll do this by forming a list of all
1557 * available clues, shuffling it, then going along one at a
1558 * time clearing each clue in turn for which doing so doesn't render the
1559 * board unsolvable. */
1560 face_list
= snewn(num_faces
, int);
1561 for (n
= 0; n
< num_faces
; ++n
) {
1565 shuffle(face_list
, num_faces
, sizeof(int), rs
);
1567 for (n
= 0; n
< num_faces
; ++n
) {
1568 saved_ret
= dup_game(ret
);
1569 ret
->clues
[face_list
[n
]] = -1;
1571 if (game_has_unique_soln(ret
, diff
)) {
1572 free_game(saved_ret
);
1584 static char *new_game_desc(game_params
*params
, random_state
*rs
,
1585 char **aux
, int interactive
)
1587 /* solution and description both use run-length encoding in obvious ways */
1590 game_state
*state
= snew(game_state
);
1591 game_state
*state_new
;
1592 params_generate_grid(params
);
1593 state
->game_grid
= g
= params
->game_grid
;
1595 state
->clues
= snewn(g
->num_faces
, signed char);
1596 state
->lines
= snewn(g
->num_edges
, char);
1598 state
->grid_type
= params
->type
;
1602 memset(state
->lines
, LINE_UNKNOWN
, g
->num_edges
);
1604 state
->solved
= state
->cheated
= FALSE
;
1606 /* Get a new random solvable board with all its clues filled in. Yes, this
1607 * can loop for ever if the params are suitably unfavourable, but
1608 * preventing games smaller than 4x4 seems to stop this happening */
1610 add_full_clues(state
, rs
);
1611 } while (!game_has_unique_soln(state
, params
->diff
));
1613 state_new
= remove_clues(state
, rs
, params
->diff
);
1618 if (params
->diff
> 0 && game_has_unique_soln(state
, params
->diff
-1)) {
1620 fprintf(stderr
, "Rejecting board, it is too easy\n");
1622 goto newboard_please
;
1625 retval
= state_to_text(state
);
1629 assert(!validate_desc(params
, retval
));
1634 static game_state
*new_game(midend
*me
, game_params
*params
, char *desc
)
1637 game_state
*state
= snew(game_state
);
1638 int empties_to_make
= 0;
1640 const char *dp
= desc
;
1642 int num_faces
, num_edges
;
1644 params_generate_grid(params
);
1645 state
->game_grid
= g
= params
->game_grid
;
1647 num_faces
= g
->num_faces
;
1648 num_edges
= g
->num_edges
;
1650 state
->clues
= snewn(num_faces
, signed char);
1651 state
->lines
= snewn(num_edges
, char);
1653 state
->solved
= state
->cheated
= FALSE
;
1655 state
->grid_type
= params
->type
;
1657 for (i
= 0; i
< num_faces
; i
++) {
1658 if (empties_to_make
) {
1660 state
->clues
[i
] = -1;
1666 if (n
>= 0 && n
< 10) {
1667 state
->clues
[i
] = n
;
1671 state
->clues
[i
] = -1;
1672 empties_to_make
= n
- 1;
1677 memset(state
->lines
, LINE_UNKNOWN
, num_edges
);
1682 enum { LOOP_NONE
=0, LOOP_SOLN
, LOOP_NOT_SOLN
};
1684 /* ----------------------------------------------------------------------
1687 * Our solver modes operate as follows. Each mode also uses the modes above it.
1690 * Just implement the rules of the game.
1693 * For each (adjacent) pair of lines through each dot we store a bit for
1694 * whether at least one of them is on and whether at most one is on. (If we
1695 * know both or neither is on that's already stored more directly.)
1698 * Use edsf data structure to make equivalence classes of lines that are
1699 * known identical to or opposite to one another.
1704 * For general grids, we consider "dlines" to be pairs of lines joined
1705 * at a dot. The lines must be adjacent around the dot, so we can think of
1706 * a dline as being a dot+face combination. Or, a dot+edge combination where
1707 * the second edge is taken to be the next clockwise edge from the dot.
1708 * Original loopy code didn't have this extra restriction of the lines being
1709 * adjacent. From my tests with square grids, this extra restriction seems to
1710 * take little, if anything, away from the quality of the puzzles.
1711 * A dline can be uniquely identified by an edge/dot combination, given that
1712 * a dline-pair always goes clockwise around its common dot. The edge/dot
1713 * combination can be represented by an edge/bool combination - if bool is
1714 * TRUE, use edge->dot1 else use edge->dot2. So the total number of dlines is
1715 * exactly twice the number of edges in the grid - although the dlines
1716 * spanning the infinite face are not all that useful to the solver.
1717 * Note that, by convention, a dline goes clockwise around its common dot,
1718 * which means the dline goes anti-clockwise around its common face.
1721 /* Helper functions for obtaining an index into an array of dlines, given
1722 * various information. We assume the grid layout conventions about how
1723 * the various lists are interleaved - see grid_make_consistent() for
1726 /* i points to the first edge of the dline pair, reading clockwise around
1728 static int dline_index_from_dot(grid
*g
, grid_dot
*d
, int i
)
1730 grid_edge
*e
= d
->edges
[i
];
1735 if (i2
== d
->order
) i2
= 0;
1738 ret
= 2 * (e
- g
->edges
) + ((e
->dot1
== d
) ?
1 : 0);
1740 printf("dline_index_from_dot: d=%d,i=%d, edges [%d,%d] - %d\n",
1741 (int)(d
- g
->dots
), i
, (int)(e
- g
->edges
),
1742 (int)(e2
- g
->edges
), ret
);
1746 /* i points to the second edge of the dline pair, reading clockwise around
1747 * the face. That is, the edges of the dline, starting at edge{i}, read
1748 * anti-clockwise around the face. By layout conventions, the common dot
1749 * of the dline will be f->dots[i] */
1750 static int dline_index_from_face(grid
*g
, grid_face
*f
, int i
)
1752 grid_edge
*e
= f
->edges
[i
];
1753 grid_dot
*d
= f
->dots
[i
];
1758 if (i2
< 0) i2
+= f
->order
;
1761 ret
= 2 * (e
- g
->edges
) + ((e
->dot1
== d
) ?
1 : 0);
1763 printf("dline_index_from_face: f=%d,i=%d, edges [%d,%d] - %d\n",
1764 (int)(f
- g
->faces
), i
, (int)(e
- g
->edges
),
1765 (int)(e2
- g
->edges
), ret
);
1769 static int is_atleastone(const char *dline_array
, int index
)
1771 return BIT_SET(dline_array
[index
], 0);
1773 static int set_atleastone(char *dline_array
, int index
)
1775 return SET_BIT(dline_array
[index
], 0);
1777 static int is_atmostone(const char *dline_array
, int index
)
1779 return BIT_SET(dline_array
[index
], 1);
1781 static int set_atmostone(char *dline_array
, int index
)
1783 return SET_BIT(dline_array
[index
], 1);
1786 static void array_setall(char *array
, char from
, char to
, int len
)
1788 char *p
= array
, *p_old
= p
;
1789 int len_remaining
= len
;
1791 while ((p
= memchr(p
, from
, len_remaining
))) {
1793 len_remaining
-= p
- p_old
;
1798 /* Helper, called when doing dline dot deductions, in the case where we
1799 * have 4 UNKNOWNs, and two of them (adjacent) have *exactly* one YES between
1800 * them (because of dline atmostone/atleastone).
1801 * On entry, edge points to the first of these two UNKNOWNs. This function
1802 * will find the opposite UNKNOWNS (if they are adjacent to one another)
1803 * and set their corresponding dline to atleastone. (Setting atmostone
1804 * already happens in earlier dline deductions) */
1805 static int dline_set_opp_atleastone(solver_state
*sstate
,
1806 grid_dot
*d
, int edge
)
1808 game_state
*state
= sstate
->state
;
1809 grid
*g
= state
->game_grid
;
1812 for (opp
= 0; opp
< N
; opp
++) {
1813 int opp_dline_index
;
1814 if (opp
== edge
|| opp
== edge
+1 || opp
== edge
-1)
1816 if (opp
== 0 && edge
== N
-1)
1818 if (opp
== N
-1 && edge
== 0)
1821 if (opp2
== N
) opp2
= 0;
1822 /* Check if opp, opp2 point to LINE_UNKNOWNs */
1823 if (state
->lines
[d
->edges
[opp
] - g
->edges
] != LINE_UNKNOWN
)
1825 if (state
->lines
[d
->edges
[opp2
] - g
->edges
] != LINE_UNKNOWN
)
1827 /* Found opposite UNKNOWNS and they're next to each other */
1828 opp_dline_index
= dline_index_from_dot(g
, d
, opp
);
1829 return set_atleastone(sstate
->normal
->dlines
, opp_dline_index
);
1835 /* Set pairs of lines around this face which are known to be identical, to
1836 * the given line_state */
1837 static int face_setall_identical(solver_state
*sstate
, int face_index
,
1838 enum line_state line_new
)
1840 /* can[dir] contains the canonical line associated with the line in
1841 * direction dir from the square in question. Similarly inv[dir] is
1842 * whether or not the line in question is inverse to its canonical
1845 game_state
*state
= sstate
->state
;
1846 grid
*g
= state
->game_grid
;
1847 grid_face
*f
= g
->faces
+ face_index
;
1850 int can1
, can2
, inv1
, inv2
;
1852 for (i
= 0; i
< N
; i
++) {
1853 int line1_index
= f
->edges
[i
] - g
->edges
;
1854 if (state
->lines
[line1_index
] != LINE_UNKNOWN
)
1856 for (j
= i
+ 1; j
< N
; j
++) {
1857 int line2_index
= f
->edges
[j
] - g
->edges
;
1858 if (state
->lines
[line2_index
] != LINE_UNKNOWN
)
1861 /* Found two UNKNOWNS */
1862 can1
= edsf_canonify(sstate
->hard
->linedsf
, line1_index
, &inv1
);
1863 can2
= edsf_canonify(sstate
->hard
->linedsf
, line2_index
, &inv2
);
1864 if (can1
== can2
&& inv1
== inv2
) {
1865 solver_set_line(sstate
, line1_index
, line_new
);
1866 solver_set_line(sstate
, line2_index
, line_new
);
1873 /* Given a dot or face, and a count of LINE_UNKNOWNs, find them and
1874 * return the edge indices into e. */
1875 static void find_unknowns(game_state
*state
,
1876 grid_edge
**edge_list
, /* Edge list to search (from a face or a dot) */
1877 int expected_count
, /* Number of UNKNOWNs (comes from solver's cache) */
1878 int *e
/* Returned edge indices */)
1881 grid
*g
= state
->game_grid
;
1882 while (c
< expected_count
) {
1883 int line_index
= *edge_list
- g
->edges
;
1884 if (state
->lines
[line_index
] == LINE_UNKNOWN
) {
1892 /* If we have a list of edges, and we know whether the number of YESs should
1893 * be odd or even, and there are only a few UNKNOWNs, we can do some simple
1894 * linedsf deductions. This can be used for both face and dot deductions.
1895 * Returns the difficulty level of the next solver that should be used,
1896 * or DIFF_MAX if no progress was made. */
1897 static int parity_deductions(solver_state
*sstate
,
1898 grid_edge
**edge_list
, /* Edge list (from a face or a dot) */
1899 int total_parity
, /* Expected number of YESs modulo 2 (either 0 or 1) */
1902 game_state
*state
= sstate
->state
;
1903 int diff
= DIFF_MAX
;
1904 int *linedsf
= sstate
->hard
->linedsf
;
1906 if (unknown_count
== 2) {
1907 /* Lines are known alike/opposite, depending on inv. */
1909 find_unknowns(state
, edge_list
, 2, e
);
1910 if (merge_lines(sstate
, e
[0], e
[1], total_parity
))
1911 diff
= min(diff
, DIFF_HARD
);
1912 } else if (unknown_count
== 3) {
1914 int can
[3]; /* canonical edges */
1915 int inv
[3]; /* whether can[x] is inverse to e[x] */
1916 find_unknowns(state
, edge_list
, 3, e
);
1917 can
[0] = edsf_canonify(linedsf
, e
[0], inv
);
1918 can
[1] = edsf_canonify(linedsf
, e
[1], inv
+1);
1919 can
[2] = edsf_canonify(linedsf
, e
[2], inv
+2);
1920 if (can
[0] == can
[1]) {
1921 if (solver_set_line(sstate
, e
[2], (total_parity
^inv
[0]^inv
[1]) ?
1922 LINE_YES
: LINE_NO
))
1923 diff
= min(diff
, DIFF_EASY
);
1925 if (can
[0] == can
[2]) {
1926 if (solver_set_line(sstate
, e
[1], (total_parity
^inv
[0]^inv
[2]) ?
1927 LINE_YES
: LINE_NO
))
1928 diff
= min(diff
, DIFF_EASY
);
1930 if (can
[1] == can
[2]) {
1931 if (solver_set_line(sstate
, e
[0], (total_parity
^inv
[1]^inv
[2]) ?
1932 LINE_YES
: LINE_NO
))
1933 diff
= min(diff
, DIFF_EASY
);
1935 } else if (unknown_count
== 4) {
1937 int can
[4]; /* canonical edges */
1938 int inv
[4]; /* whether can[x] is inverse to e[x] */
1939 find_unknowns(state
, edge_list
, 4, e
);
1940 can
[0] = edsf_canonify(linedsf
, e
[0], inv
);
1941 can
[1] = edsf_canonify(linedsf
, e
[1], inv
+1);
1942 can
[2] = edsf_canonify(linedsf
, e
[2], inv
+2);
1943 can
[3] = edsf_canonify(linedsf
, e
[3], inv
+3);
1944 if (can
[0] == can
[1]) {
1945 if (merge_lines(sstate
, e
[2], e
[3], total_parity
^inv
[0]^inv
[1]))
1946 diff
= min(diff
, DIFF_HARD
);
1947 } else if (can
[0] == can
[2]) {
1948 if (merge_lines(sstate
, e
[1], e
[3], total_parity
^inv
[0]^inv
[2]))
1949 diff
= min(diff
, DIFF_HARD
);
1950 } else if (can
[0] == can
[3]) {
1951 if (merge_lines(sstate
, e
[1], e
[2], total_parity
^inv
[0]^inv
[3]))
1952 diff
= min(diff
, DIFF_HARD
);
1953 } else if (can
[1] == can
[2]) {
1954 if (merge_lines(sstate
, e
[0], e
[3], total_parity
^inv
[1]^inv
[2]))
1955 diff
= min(diff
, DIFF_HARD
);
1956 } else if (can
[1] == can
[3]) {
1957 if (merge_lines(sstate
, e
[0], e
[2], total_parity
^inv
[1]^inv
[3]))
1958 diff
= min(diff
, DIFF_HARD
);
1959 } else if (can
[2] == can
[3]) {
1960 if (merge_lines(sstate
, e
[0], e
[1], total_parity
^inv
[2]^inv
[3]))
1961 diff
= min(diff
, DIFF_HARD
);
1969 * These are the main solver functions.
1971 * Their return values are diff values corresponding to the lowest mode solver
1972 * that would notice the work that they have done. For example if the normal
1973 * mode solver adds actual lines or crosses, it will return DIFF_EASY as the
1974 * easy mode solver might be able to make progress using that. It doesn't make
1975 * sense for one of them to return a diff value higher than that of the
1978 * Each function returns the lowest value it can, as early as possible, in
1979 * order to try and pass as much work as possible back to the lower level
1980 * solvers which progress more quickly.
1983 /* PROPOSED NEW DESIGN:
1984 * We have a work queue consisting of 'events' notifying us that something has
1985 * happened that a particular solver mode might be interested in. For example
1986 * the hard mode solver might do something that helps the normal mode solver at
1987 * dot [x,y] in which case it will enqueue an event recording this fact. Then
1988 * we pull events off the work queue, and hand each in turn to the solver that
1989 * is interested in them. If a solver reports that it failed we pass the same
1990 * event on to progressively more advanced solvers and the loop detector. Once
1991 * we've exhausted an event, or it has helped us progress, we drop it and
1992 * continue to the next one. The events are sorted first in order of solver
1993 * complexity (easy first) then order of insertion (oldest first).
1994 * Once we run out of events we loop over each permitted solver in turn
1995 * (easiest first) until either a deduction is made (and an event therefore
1996 * emerges) or no further deductions can be made (in which case we've failed).
1999 * * How do we 'loop over' a solver when both dots and squares are concerned.
2000 * Answer: first all squares then all dots.
2003 static int easy_mode_deductions(solver_state
*sstate
)
2005 int i
, current_yes
, current_no
;
2006 game_state
*state
= sstate
->state
;
2007 grid
*g
= state
->game_grid
;
2008 int diff
= DIFF_MAX
;
2010 /* Per-face deductions */
2011 for (i
= 0; i
< g
->num_faces
; i
++) {
2012 grid_face
*f
= g
->faces
+ i
;
2014 if (sstate
->face_solved
[i
])
2017 current_yes
= sstate
->face_yes_count
[i
];
2018 current_no
= sstate
->face_no_count
[i
];
2020 if (current_yes
+ current_no
== f
->order
) {
2021 sstate
->face_solved
[i
] = TRUE
;
2025 if (state
->clues
[i
] < 0)
2028 if (state
->clues
[i
] < current_yes
) {
2029 sstate
->solver_status
= SOLVER_MISTAKE
;
2032 if (state
->clues
[i
] == current_yes
) {
2033 if (face_setall(sstate
, i
, LINE_UNKNOWN
, LINE_NO
))
2034 diff
= min(diff
, DIFF_EASY
);
2035 sstate
->face_solved
[i
] = TRUE
;
2039 if (f
->order
- state
->clues
[i
] < current_no
) {
2040 sstate
->solver_status
= SOLVER_MISTAKE
;
2043 if (f
->order
- state
->clues
[i
] == current_no
) {
2044 if (face_setall(sstate
, i
, LINE_UNKNOWN
, LINE_YES
))
2045 diff
= min(diff
, DIFF_EASY
);
2046 sstate
->face_solved
[i
] = TRUE
;
2051 check_caches(sstate
);
2053 /* Per-dot deductions */
2054 for (i
= 0; i
< g
->num_dots
; i
++) {
2055 grid_dot
*d
= g
->dots
+ i
;
2056 int yes
, no
, unknown
;
2058 if (sstate
->dot_solved
[i
])
2061 yes
= sstate
->dot_yes_count
[i
];
2062 no
= sstate
->dot_no_count
[i
];
2063 unknown
= d
->order
- yes
- no
;
2067 sstate
->dot_solved
[i
] = TRUE
;
2068 } else if (unknown
== 1) {
2069 dot_setall(sstate
, i
, LINE_UNKNOWN
, LINE_NO
);
2070 diff
= min(diff
, DIFF_EASY
);
2071 sstate
->dot_solved
[i
] = TRUE
;
2073 } else if (yes
== 1) {
2075 sstate
->solver_status
= SOLVER_MISTAKE
;
2077 } else if (unknown
== 1) {
2078 dot_setall(sstate
, i
, LINE_UNKNOWN
, LINE_YES
);
2079 diff
= min(diff
, DIFF_EASY
);
2081 } else if (yes
== 2) {
2083 dot_setall(sstate
, i
, LINE_UNKNOWN
, LINE_NO
);
2084 diff
= min(diff
, DIFF_EASY
);
2086 sstate
->dot_solved
[i
] = TRUE
;
2088 sstate
->solver_status
= SOLVER_MISTAKE
;
2093 check_caches(sstate
);
2098 static int normal_mode_deductions(solver_state
*sstate
)
2100 game_state
*state
= sstate
->state
;
2101 grid
*g
= state
->game_grid
;
2102 char *dlines
= sstate
->normal
->dlines
;
2104 int diff
= DIFF_MAX
;
2106 /* ------ Face deductions ------ */
2108 /* Given a set of dline atmostone/atleastone constraints, need to figure
2109 * out if we can deduce any further info. For more general faces than
2110 * squares, this turns out to be a tricky problem.
2111 * The approach taken here is to define (per face) NxN matrices:
2112 * "maxs" and "mins".
2113 * The entries maxs(j,k) and mins(j,k) define the upper and lower limits
2114 * for the possible number of edges that are YES between positions j and k
2115 * going clockwise around the face. Can think of j and k as marking dots
2116 * around the face (recall the labelling scheme: edge0 joins dot0 to dot1,
2117 * edge1 joins dot1 to dot2 etc).
2118 * Trivially, mins(j,j) = maxs(j,j) = 0, and we don't even bother storing
2119 * these. mins(j,j+1) and maxs(j,j+1) are determined by whether edge{j}
2120 * is YES, NO or UNKNOWN. mins(j,j+2) and maxs(j,j+2) are related to
2121 * the dline atmostone/atleastone status for edges j and j+1.
2123 * Then we calculate the remaining entries recursively. We definitely
2125 * mins(j,k) >= { mins(j,u) + mins(u,k) } for any u between j and k.
2126 * This is because any valid placement of YESs between j and k must give
2127 * a valid placement between j and u, and also between u and k.
2128 * I believe it's sufficient to use just the two values of u:
2129 * j+1 and j+2. Seems to work well in practice - the bounds we compute
2130 * are rigorous, even if they might not be best-possible.
2132 * Once we have maxs and mins calculated, we can make inferences about
2133 * each dline{j,j+1} by looking at the possible complementary edge-counts
2134 * mins(j+2,j) and maxs(j+2,j) and comparing these with the face clue.
2135 * As well as dlines, we can make similar inferences about single edges.
2136 * For example, consider a pentagon with clue 3, and we know at most one
2137 * of (edge0, edge1) is YES, and at most one of (edge2, edge3) is YES.
2138 * We could then deduce edge4 is YES, because maxs(0,4) would be 2, so
2139 * that final edge would have to be YES to make the count up to 3.
2142 /* Much quicker to allocate arrays on the stack than the heap, so
2143 * define the largest possible face size, and base our array allocations
2144 * on that. We check this with an assertion, in case someone decides to
2145 * make a grid which has larger faces than this. Note, this algorithm
2146 * could get quite expensive if there are many large faces. */
2147 #define MAX_FACE_SIZE 8
2149 for (i
= 0; i
< g
->num_faces
; i
++) {
2150 int maxs
[MAX_FACE_SIZE
][MAX_FACE_SIZE
];
2151 int mins
[MAX_FACE_SIZE
][MAX_FACE_SIZE
];
2152 grid_face
*f
= g
->faces
+ i
;
2155 int clue
= state
->clues
[i
];
2156 assert(N
<= MAX_FACE_SIZE
);
2157 if (sstate
->face_solved
[i
])
2159 if (clue
< 0) continue;
2161 /* Calculate the (j,j+1) entries */
2162 for (j
= 0; j
< N
; j
++) {
2163 int edge_index
= f
->edges
[j
] - g
->edges
;
2165 enum line_state line1
= state
->lines
[edge_index
];
2166 enum line_state line2
;
2170 maxs
[j
][k
] = (line1
== LINE_NO
) ?
0 : 1;
2171 mins
[j
][k
] = (line1
== LINE_YES
) ?
1 : 0;
2172 /* Calculate the (j,j+2) entries */
2173 dline_index
= dline_index_from_face(g
, f
, k
);
2174 edge_index
= f
->edges
[k
] - g
->edges
;
2175 line2
= state
->lines
[edge_index
];
2181 if (line1
== LINE_NO
) tmp
--;
2182 if (line2
== LINE_NO
) tmp
--;
2183 if (tmp
== 2 && is_atmostone(dlines
, dline_index
))
2189 if (line1
== LINE_YES
) tmp
++;
2190 if (line2
== LINE_YES
) tmp
++;
2191 if (tmp
== 0 && is_atleastone(dlines
, dline_index
))
2196 /* Calculate the (j,j+m) entries for m between 3 and N-1 */
2197 for (m
= 3; m
< N
; m
++) {
2198 for (j
= 0; j
< N
; j
++) {
2206 maxs
[j
][k
] = maxs
[j
][u
] + maxs
[u
][k
];
2207 mins
[j
][k
] = mins
[j
][u
] + mins
[u
][k
];
2208 tmp
= maxs
[j
][v
] + maxs
[v
][k
];
2209 maxs
[j
][k
] = min(maxs
[j
][k
], tmp
);
2210 tmp
= mins
[j
][v
] + mins
[v
][k
];
2211 mins
[j
][k
] = max(mins
[j
][k
], tmp
);
2215 /* See if we can make any deductions */
2216 for (j
= 0; j
< N
; j
++) {
2218 grid_edge
*e
= f
->edges
[j
];
2219 int line_index
= e
- g
->edges
;
2222 if (state
->lines
[line_index
] != LINE_UNKNOWN
)
2227 /* minimum YESs in the complement of this edge */
2228 if (mins
[k
][j
] > clue
) {
2229 sstate
->solver_status
= SOLVER_MISTAKE
;
2232 if (mins
[k
][j
] == clue
) {
2233 /* setting this edge to YES would make at least
2234 * (clue+1) edges - contradiction */
2235 solver_set_line(sstate
, line_index
, LINE_NO
);
2236 diff
= min(diff
, DIFF_EASY
);
2238 if (maxs
[k
][j
] < clue
- 1) {
2239 sstate
->solver_status
= SOLVER_MISTAKE
;
2242 if (maxs
[k
][j
] == clue
- 1) {
2243 /* Only way to satisfy the clue is to set edge{j} as YES */
2244 solver_set_line(sstate
, line_index
, LINE_YES
);
2245 diff
= min(diff
, DIFF_EASY
);
2248 /* Now see if we can make dline deduction for edges{j,j+1} */
2250 if (state
->lines
[e
- g
->edges
] != LINE_UNKNOWN
)
2251 /* Only worth doing this for an UNKNOWN,UNKNOWN pair.
2252 * Dlines where one of the edges is known, are handled in the
2256 dline_index
= dline_index_from_face(g
, f
, k
);
2260 /* minimum YESs in the complement of this dline */
2261 if (mins
[k
][j
] > clue
- 2) {
2262 /* Adding 2 YESs would break the clue */
2263 if (set_atmostone(dlines
, dline_index
))
2264 diff
= min(diff
, DIFF_NORMAL
);
2266 /* maximum YESs in the complement of this dline */
2267 if (maxs
[k
][j
] < clue
) {
2268 /* Adding 2 NOs would mean not enough YESs */
2269 if (set_atleastone(dlines
, dline_index
))
2270 diff
= min(diff
, DIFF_NORMAL
);
2275 if (diff
< DIFF_NORMAL
)
2278 /* ------ Dot deductions ------ */
2280 for (i
= 0; i
< g
->num_dots
; i
++) {
2281 grid_dot
*d
= g
->dots
+ i
;
2283 int yes
, no
, unknown
;
2285 if (sstate
->dot_solved
[i
])
2287 yes
= sstate
->dot_yes_count
[i
];
2288 no
= sstate
->dot_no_count
[i
];
2289 unknown
= N
- yes
- no
;
2291 for (j
= 0; j
< N
; j
++) {
2294 int line1_index
, line2_index
;
2295 enum line_state line1
, line2
;
2298 dline_index
= dline_index_from_dot(g
, d
, j
);
2299 line1_index
= d
->edges
[j
] - g
->edges
;
2300 line2_index
= d
->edges
[k
] - g
->edges
;
2301 line1
= state
->lines
[line1_index
];
2302 line2
= state
->lines
[line2_index
];
2304 /* Infer dline state from line state */
2305 if (line1
== LINE_NO
|| line2
== LINE_NO
) {
2306 if (set_atmostone(dlines
, dline_index
))
2307 diff
= min(diff
, DIFF_NORMAL
);
2309 if (line1
== LINE_YES
|| line2
== LINE_YES
) {
2310 if (set_atleastone(dlines
, dline_index
))
2311 diff
= min(diff
, DIFF_NORMAL
);
2313 /* Infer line state from dline state */
2314 if (is_atmostone(dlines
, dline_index
)) {
2315 if (line1
== LINE_YES
&& line2
== LINE_UNKNOWN
) {
2316 solver_set_line(sstate
, line2_index
, LINE_NO
);
2317 diff
= min(diff
, DIFF_EASY
);
2319 if (line2
== LINE_YES
&& line1
== LINE_UNKNOWN
) {
2320 solver_set_line(sstate
, line1_index
, LINE_NO
);
2321 diff
= min(diff
, DIFF_EASY
);
2324 if (is_atleastone(dlines
, dline_index
)) {
2325 if (line1
== LINE_NO
&& line2
== LINE_UNKNOWN
) {
2326 solver_set_line(sstate
, line2_index
, LINE_YES
);
2327 diff
= min(diff
, DIFF_EASY
);
2329 if (line2
== LINE_NO
&& line1
== LINE_UNKNOWN
) {
2330 solver_set_line(sstate
, line1_index
, LINE_YES
);
2331 diff
= min(diff
, DIFF_EASY
);
2334 /* Deductions that depend on the numbers of lines.
2335 * Only bother if both lines are UNKNOWN, otherwise the
2336 * easy-mode solver (or deductions above) would have taken
2338 if (line1
!= LINE_UNKNOWN
|| line2
!= LINE_UNKNOWN
)
2341 if (yes
== 0 && unknown
== 2) {
2342 /* Both these unknowns must be identical. If we know
2343 * atmostone or atleastone, we can make progress. */
2344 if (is_atmostone(dlines
, dline_index
)) {
2345 solver_set_line(sstate
, line1_index
, LINE_NO
);
2346 solver_set_line(sstate
, line2_index
, LINE_NO
);
2347 diff
= min(diff
, DIFF_EASY
);
2349 if (is_atleastone(dlines
, dline_index
)) {
2350 solver_set_line(sstate
, line1_index
, LINE_YES
);
2351 solver_set_line(sstate
, line2_index
, LINE_YES
);
2352 diff
= min(diff
, DIFF_EASY
);
2356 if (set_atmostone(dlines
, dline_index
))
2357 diff
= min(diff
, DIFF_NORMAL
);
2359 if (set_atleastone(dlines
, dline_index
))
2360 diff
= min(diff
, DIFF_NORMAL
);
2364 /* If we have atleastone set for this dline, infer
2365 * atmostone for each "opposite" dline (that is, each
2366 * dline without edges in common with this one).
2367 * Again, this test is only worth doing if both these
2368 * lines are UNKNOWN. For if one of these lines were YES,
2369 * the (yes == 1) test above would kick in instead. */
2370 if (is_atleastone(dlines
, dline_index
)) {
2372 for (opp
= 0; opp
< N
; opp
++) {
2373 int opp_dline_index
;
2374 if (opp
== j
|| opp
== j
+1 || opp
== j
-1)
2376 if (j
== 0 && opp
== N
-1)
2378 if (j
== N
-1 && opp
== 0)
2380 opp_dline_index
= dline_index_from_dot(g
, d
, opp
);
2381 if (set_atmostone(dlines
, opp_dline_index
))
2382 diff
= min(diff
, DIFF_NORMAL
);
2385 if (yes
== 0 && is_atmostone(dlines
, dline_index
)) {
2386 /* This dline has *exactly* one YES and there are no
2387 * other YESs. This allows more deductions. */
2389 /* Third unknown must be YES */
2390 for (opp
= 0; opp
< N
; opp
++) {
2392 if (opp
== j
|| opp
== k
)
2394 opp_index
= d
->edges
[opp
] - g
->edges
;
2395 if (state
->lines
[opp_index
] == LINE_UNKNOWN
) {
2396 solver_set_line(sstate
, opp_index
, LINE_YES
);
2397 diff
= min(diff
, DIFF_EASY
);
2400 } else if (unknown
== 4) {
2401 /* Exactly one of opposite UNKNOWNS is YES. We've
2402 * already set atmostone, so set atleastone as well.
2404 if (dline_set_opp_atleastone(sstate
, d
, j
))
2405 diff
= min(diff
, DIFF_NORMAL
);
2414 static int hard_mode_deductions(solver_state
*sstate
)
2416 game_state
*state
= sstate
->state
;
2417 grid
*g
= state
->game_grid
;
2418 char *dlines
= sstate
->normal
->dlines
;
2420 int diff
= DIFF_MAX
;
2423 /* ------ Face deductions ------ */
2425 /* A fully-general linedsf deduction seems overly complicated
2426 * (I suspect the problem is NP-complete, though in practice it might just
2427 * be doable because faces are limited in size).
2428 * For simplicity, we only consider *pairs* of LINE_UNKNOWNS that are
2429 * known to be identical. If setting them both to YES (or NO) would break
2430 * the clue, set them to NO (or YES). */
2432 for (i
= 0; i
< g
->num_faces
; i
++) {
2433 int N
, yes
, no
, unknown
;
2436 if (sstate
->face_solved
[i
])
2438 clue
= state
->clues
[i
];
2442 N
= g
->faces
[i
].order
;
2443 yes
= sstate
->face_yes_count
[i
];
2444 if (yes
+ 1 == clue
) {
2445 if (face_setall_identical(sstate
, i
, LINE_NO
))
2446 diff
= min(diff
, DIFF_EASY
);
2448 no
= sstate
->face_no_count
[i
];
2449 if (no
+ 1 == N
- clue
) {
2450 if (face_setall_identical(sstate
, i
, LINE_YES
))
2451 diff
= min(diff
, DIFF_EASY
);
2454 /* Reload YES count, it might have changed */
2455 yes
= sstate
->face_yes_count
[i
];
2456 unknown
= N
- no
- yes
;
2458 /* Deductions with small number of LINE_UNKNOWNs, based on overall
2459 * parity of lines. */
2460 diff_tmp
= parity_deductions(sstate
, g
->faces
[i
].edges
,
2461 (clue
- yes
) % 2, unknown
);
2462 diff
= min(diff
, diff_tmp
);
2465 /* ------ Dot deductions ------ */
2466 for (i
= 0; i
< g
->num_dots
; i
++) {
2467 grid_dot
*d
= g
->dots
+ i
;
2470 int yes
, no
, unknown
;
2471 /* Go through dlines, and do any dline<->linedsf deductions wherever
2472 * we find two UNKNOWNS. */
2473 for (j
= 0; j
< N
; j
++) {
2474 int dline_index
= dline_index_from_dot(g
, d
, j
);
2477 int can1
, can2
, inv1
, inv2
;
2479 line1_index
= d
->edges
[j
] - g
->edges
;
2480 if (state
->lines
[line1_index
] != LINE_UNKNOWN
)
2483 if (j2
== N
) j2
= 0;
2484 line2_index
= d
->edges
[j2
] - g
->edges
;
2485 if (state
->lines
[line2_index
] != LINE_UNKNOWN
)
2487 /* Infer dline flags from linedsf */
2488 can1
= edsf_canonify(sstate
->hard
->linedsf
, line1_index
, &inv1
);
2489 can2
= edsf_canonify(sstate
->hard
->linedsf
, line2_index
, &inv2
);
2490 if (can1
== can2
&& inv1
!= inv2
) {
2491 /* These are opposites, so set dline atmostone/atleastone */
2492 if (set_atmostone(dlines
, dline_index
))
2493 diff
= min(diff
, DIFF_NORMAL
);
2494 if (set_atleastone(dlines
, dline_index
))
2495 diff
= min(diff
, DIFF_NORMAL
);
2498 /* Infer linedsf from dline flags */
2499 if (is_atmostone(dlines
, dline_index
)
2500 && is_atleastone(dlines
, dline_index
)) {
2501 if (merge_lines(sstate
, line1_index
, line2_index
, 1))
2502 diff
= min(diff
, DIFF_HARD
);
2506 /* Deductions with small number of LINE_UNKNOWNs, based on overall
2507 * parity of lines. */
2508 yes
= sstate
->dot_yes_count
[i
];
2509 no
= sstate
->dot_no_count
[i
];
2510 unknown
= N
- yes
- no
;
2511 diff_tmp
= parity_deductions(sstate
, d
->edges
,
2513 diff
= min(diff
, diff_tmp
);
2516 /* ------ Edge dsf deductions ------ */
2518 /* If the state of a line is known, deduce the state of its canonical line
2519 * too, and vice versa. */
2520 for (i
= 0; i
< g
->num_edges
; i
++) {
2523 can
= edsf_canonify(sstate
->hard
->linedsf
, i
, &inv
);
2526 s
= sstate
->state
->lines
[can
];
2527 if (s
!= LINE_UNKNOWN
) {
2528 if (solver_set_line(sstate
, i
, inv ?
OPP(s
) : s
))
2529 diff
= min(diff
, DIFF_EASY
);
2531 s
= sstate
->state
->lines
[i
];
2532 if (s
!= LINE_UNKNOWN
) {
2533 if (solver_set_line(sstate
, can
, inv ?
OPP(s
) : s
))
2534 diff
= min(diff
, DIFF_EASY
);
2542 static int loop_deductions(solver_state
*sstate
)
2544 int edgecount
= 0, clues
= 0, satclues
= 0, sm1clues
= 0;
2545 game_state
*state
= sstate
->state
;
2546 grid
*g
= state
->game_grid
;
2547 int shortest_chainlen
= g
->num_dots
;
2548 int loop_found
= FALSE
;
2550 int progress
= FALSE
;
2554 * Go through the grid and update for all the new edges.
2555 * Since merge_dots() is idempotent, the simplest way to
2556 * do this is just to update for _all_ the edges.
2557 * Also, while we're here, we count the edges.
2559 for (i
= 0; i
< g
->num_edges
; i
++) {
2560 if (state
->lines
[i
] == LINE_YES
) {
2561 loop_found
|= merge_dots(sstate
, i
);
2567 * Count the clues, count the satisfied clues, and count the
2568 * satisfied-minus-one clues.
2570 for (i
= 0; i
< g
->num_faces
; i
++) {
2571 int c
= state
->clues
[i
];
2573 int o
= sstate
->face_yes_count
[i
];
2582 for (i
= 0; i
< g
->num_dots
; ++i
) {
2584 sstate
->looplen
[dsf_canonify(sstate
->dotdsf
, i
)];
2585 if (dots_connected
> 1)
2586 shortest_chainlen
= min(shortest_chainlen
, dots_connected
);
2589 assert(sstate
->solver_status
== SOLVER_INCOMPLETE
);
2591 if (satclues
== clues
&& shortest_chainlen
== edgecount
) {
2592 sstate
->solver_status
= SOLVER_SOLVED
;
2593 /* This discovery clearly counts as progress, even if we haven't
2594 * just added any lines or anything */
2596 goto finished_loop_deductionsing
;
2600 * Now go through looking for LINE_UNKNOWN edges which
2601 * connect two dots that are already in the same
2602 * equivalence class. If we find one, test to see if the
2603 * loop it would create is a solution.
2605 for (i
= 0; i
< g
->num_edges
; i
++) {
2606 grid_edge
*e
= g
->edges
+ i
;
2607 int d1
= e
->dot1
- g
->dots
;
2608 int d2
= e
->dot2
- g
->dots
;
2610 if (state
->lines
[i
] != LINE_UNKNOWN
)
2613 eqclass
= dsf_canonify(sstate
->dotdsf
, d1
);
2614 if (eqclass
!= dsf_canonify(sstate
->dotdsf
, d2
))
2617 val
= LINE_NO
; /* loop is bad until proven otherwise */
2620 * This edge would form a loop. Next
2621 * question: how long would the loop be?
2622 * Would it equal the total number of edges
2623 * (plus the one we'd be adding if we added
2626 if (sstate
->looplen
[eqclass
] == edgecount
+ 1) {
2630 * This edge would form a loop which
2631 * took in all the edges in the entire
2632 * grid. So now we need to work out
2633 * whether it would be a valid solution
2634 * to the puzzle, which means we have to
2635 * check if it satisfies all the clues.
2636 * This means that every clue must be
2637 * either satisfied or satisfied-minus-
2638 * 1, and also that the number of
2639 * satisfied-minus-1 clues must be at
2640 * most two and they must lie on either
2641 * side of this edge.
2645 int f
= e
->face1
- g
->faces
;
2646 int c
= state
->clues
[f
];
2647 if (c
>= 0 && sstate
->face_yes_count
[f
] == c
- 1)
2651 int f
= e
->face2
- g
->faces
;
2652 int c
= state
->clues
[f
];
2653 if (c
>= 0 && sstate
->face_yes_count
[f
] == c
- 1)
2656 if (sm1clues
== sm1_nearby
&&
2657 sm1clues
+ satclues
== clues
) {
2658 val
= LINE_YES
; /* loop is good! */
2663 * Right. Now we know that adding this edge
2664 * would form a loop, and we know whether
2665 * that loop would be a viable solution or
2668 * If adding this edge produces a solution,
2669 * then we know we've found _a_ solution but
2670 * we don't know that it's _the_ solution -
2671 * if it were provably the solution then
2672 * we'd have deduced this edge some time ago
2673 * without the need to do loop detection. So
2674 * in this state we return SOLVER_AMBIGUOUS,
2675 * which has the effect that hitting Solve
2676 * on a user-provided puzzle will fill in a
2677 * solution but using the solver to
2678 * construct new puzzles won't consider this
2679 * a reasonable deduction for the user to
2682 progress
= solver_set_line(sstate
, i
, val
);
2683 assert(progress
== TRUE
);
2684 if (val
== LINE_YES
) {
2685 sstate
->solver_status
= SOLVER_AMBIGUOUS
;
2686 goto finished_loop_deductionsing
;
2690 finished_loop_deductionsing
:
2691 return progress ? DIFF_EASY
: DIFF_MAX
;
2694 /* This will return a dynamically allocated solver_state containing the (more)
2696 static solver_state
*solve_game_rec(const solver_state
*sstate_start
,
2699 solver_state
*sstate
, *sstate_saved
;
2700 int solver_progress
;
2703 /* Indicates which solver we should call next. This is a sensible starting
2705 int current_solver
= DIFF_EASY
, next_solver
;
2706 sstate
= dup_solver_state(sstate_start
);
2708 /* Cache the values of some variables for readability */
2709 state
= sstate
->state
;
2711 sstate_saved
= NULL
;
2713 solver_progress
= FALSE
;
2715 check_caches(sstate
);
2718 if (sstate
->solver_status
== SOLVER_MISTAKE
)
2721 next_solver
= solver_fns
[current_solver
](sstate
);
2723 if (next_solver
== DIFF_MAX
) {
2724 if (current_solver
< diff
&& current_solver
+ 1 < DIFF_MAX
) {
2725 /* Try next beefier solver */
2726 next_solver
= current_solver
+ 1;
2728 next_solver
= loop_deductions(sstate
);
2732 if (sstate
->solver_status
== SOLVER_SOLVED
||
2733 sstate
->solver_status
== SOLVER_AMBIGUOUS
) {
2734 /* fprintf(stderr, "Solver completed\n"); */
2738 /* Once we've looped over all permitted solvers then the loop
2739 * deductions without making any progress, we'll exit this while loop */
2740 current_solver
= next_solver
;
2741 } while (current_solver
< DIFF_MAX
);
2743 if (sstate
->solver_status
== SOLVER_SOLVED
||
2744 sstate
->solver_status
== SOLVER_AMBIGUOUS
) {
2745 /* s/LINE_UNKNOWN/LINE_NO/g */
2746 array_setall(sstate
->state
->lines
, LINE_UNKNOWN
, LINE_NO
,
2747 sstate
->state
->game_grid
->num_edges
);
2754 static char *solve_game(game_state
*state
, game_state
*currstate
,
2755 char *aux
, char **error
)
2758 solver_state
*sstate
, *new_sstate
;
2760 sstate
= new_solver_state(state
, DIFF_MAX
);
2761 new_sstate
= solve_game_rec(sstate
, DIFF_MAX
);
2763 if (new_sstate
->solver_status
== SOLVER_SOLVED
) {
2764 soln
= encode_solve_move(new_sstate
->state
);
2765 } else if (new_sstate
->solver_status
== SOLVER_AMBIGUOUS
) {
2766 soln
= encode_solve_move(new_sstate
->state
);
2767 /**error = "Solver found ambiguous solutions"; */
2769 soln
= encode_solve_move(new_sstate
->state
);
2770 /**error = "Solver failed"; */
2773 free_solver_state(new_sstate
);
2774 free_solver_state(sstate
);
2779 /* ----------------------------------------------------------------------
2780 * Drawing and mouse-handling
2783 static char *interpret_move(game_state
*state
, game_ui
*ui
, game_drawstate
*ds
,
2784 int x
, int y
, int button
)
2786 grid
*g
= state
->game_grid
;
2790 char button_char
= ' ';
2791 enum line_state old_state
;
2793 button
&= ~MOD_MASK
;
2795 /* Convert mouse-click (x,y) to grid coordinates */
2796 x
-= BORDER(ds
->tilesize
);
2797 y
-= BORDER(ds
->tilesize
);
2798 x
= x
* g
->tilesize
/ ds
->tilesize
;
2799 y
= y
* g
->tilesize
/ ds
->tilesize
;
2803 e
= grid_nearest_edge(g
, x
, y
);
2809 /* I think it's only possible to play this game with mouse clicks, sorry */
2810 /* Maybe will add mouse drag support some time */
2811 old_state
= state
->lines
[i
];
2815 switch (old_state
) {
2829 switch (old_state
) {
2844 sprintf(buf
, "%d%c", i
, (int)button_char
);
2850 static game_state
*execute_move(game_state
*state
, char *move
)
2853 game_state
*newstate
= dup_game(state
);
2854 grid
*g
= state
->game_grid
;
2856 if (move
[0] == 'S') {
2858 newstate
->cheated
= TRUE
;
2863 move
+= strspn(move
, "1234567890");
2864 switch (*(move
++)) {
2866 newstate
->lines
[i
] = LINE_YES
;
2869 newstate
->lines
[i
] = LINE_NO
;
2872 newstate
->lines
[i
] = LINE_UNKNOWN
;
2880 * Check for completion.
2882 for (i
= 0; i
< g
->num_edges
; i
++) {
2883 if (newstate
->lines
[i
] == LINE_YES
)
2886 if (i
< g
->num_edges
) {
2888 grid_edge
*start_edge
= g
->edges
+ i
;
2889 grid_edge
*e
= start_edge
;
2890 grid_dot
*d
= e
->dot1
;
2892 * We've found an edge i. Follow it round
2893 * to see if it's part of a loop.
2898 int order
= dot_order(newstate
, d
- g
->dots
, LINE_YES
);
2900 goto completion_check_done
;
2902 /* Find other edge around this dot */
2903 for (j
= 0; j
< d
->order
; j
++) {
2904 grid_edge
*e2
= d
->edges
[j
];
2905 if (e2
!= e
&& newstate
->lines
[e2
- g
->edges
] == LINE_YES
)
2908 assert(j
!= d
->order
); /* dot_order guarantees success */
2911 d
= (e
->dot1
== d
) ? e
->dot2
: e
->dot1
;
2914 if (e
== start_edge
)
2919 * We've traced our way round a loop, and we know how many
2920 * line segments were involved. Count _all_ the line
2921 * segments in the grid, to see if the loop includes them
2925 for (i
= 0; i
< g
->num_edges
; i
++) {
2926 if (newstate
->lines
[i
] == LINE_YES
)
2929 assert(count
>= looplen
);
2930 if (count
!= looplen
)
2931 goto completion_check_done
;
2934 * The grid contains one closed loop and nothing else.
2935 * Check that all the clues are satisfied.
2937 for (i
= 0; i
< g
->num_faces
; i
++) {
2938 int c
= newstate
->clues
[i
];
2940 if (face_order(newstate
, i
, LINE_YES
) != c
) {
2941 goto completion_check_done
;
2949 newstate
->solved
= TRUE
;
2952 completion_check_done
:
2956 free_game(newstate
);
2960 /* ----------------------------------------------------------------------
2964 /* Convert from grid coordinates to screen coordinates */
2965 static void grid_to_screen(const game_drawstate
*ds
, const grid
*g
,
2966 int grid_x
, int grid_y
, int *x
, int *y
)
2968 *x
= grid_x
- g
->lowest_x
;
2969 *y
= grid_y
- g
->lowest_y
;
2970 *x
= *x
* ds
->tilesize
/ g
->tilesize
;
2971 *y
= *y
* ds
->tilesize
/ g
->tilesize
;
2972 *x
+= BORDER(ds
->tilesize
);
2973 *y
+= BORDER(ds
->tilesize
);
2976 /* Returns (into x,y) position of centre of face for rendering the text clue.
2978 static void face_text_pos(const game_drawstate
*ds
, const grid
*g
,
2979 const grid_face
*f
, int *x
, int *y
)
2983 /* Simplest solution is the centroid. Might not work in some cases. */
2985 /* Another algorithm to look into:
2986 * Find the midpoints of the sides, find the bounding-box,
2987 * then take the centre of that. */
2989 /* Best solution probably involves incentres (inscribed circles) */
2991 int sx
= 0, sy
= 0; /* sums */
2992 for (i
= 0; i
< f
->order
; i
++) {
2993 grid_dot
*d
= f
->dots
[i
];
3000 /* convert to screen coordinates */
3001 grid_to_screen(ds
, g
, sx
, sy
, x
, y
);
3004 static void game_redraw(drawing
*dr
, game_drawstate
*ds
, game_state
*oldstate
,
3005 game_state
*state
, int dir
, game_ui
*ui
,
3006 float animtime
, float flashtime
)
3008 grid
*g
= state
->game_grid
;
3009 int border
= BORDER(ds
->tilesize
);
3012 int line_colour
, flash_changed
;
3018 * The initial contents of the window are not guaranteed and
3019 * can vary with front ends. To be on the safe side, all games
3020 * should start by drawing a big background-colour rectangle
3021 * covering the whole window.
3023 int grid_width
= g
->highest_x
- g
->lowest_x
;
3024 int grid_height
= g
->highest_y
- g
->lowest_y
;
3025 int w
= grid_width
* ds
->tilesize
/ g
->tilesize
;
3026 int h
= grid_height
* ds
->tilesize
/ g
->tilesize
;
3027 draw_rect(dr
, 0, 0, w
+ 2 * border
, h
+ 2 * border
, COL_BACKGROUND
);
3030 for (i
= 0; i
< g
->num_faces
; i
++) {
3034 c
[0] = CLUE2CHAR(state
->clues
[i
]);
3037 face_text_pos(ds
, g
, f
, &x
, &y
);
3038 draw_text(dr
, x
, y
, FONT_VARIABLE
, ds
->tilesize
/2,
3039 ALIGN_VCENTRE
| ALIGN_HCENTRE
, COL_FOREGROUND
, c
);
3041 draw_update(dr
, 0, 0, w
+ 2 * border
, h
+ 2 * border
);
3044 if (flashtime
> 0 &&
3045 (flashtime
<= FLASH_TIME
/3 ||
3046 flashtime
>= FLASH_TIME
*2/3)) {
3047 flash_changed
= !ds
->flashing
;
3048 ds
->flashing
= TRUE
;
3050 flash_changed
= ds
->flashing
;
3051 ds
->flashing
= FALSE
;
3054 /* Some platforms may perform anti-aliasing, which may prevent clean
3055 * repainting of lines when the colour is changed.
3056 * If a line needs to be over-drawn in a different colour, erase a
3057 * bounding-box around the line, then flag all nearby objects for redraw.
3060 const char redraw_flag
= 1<<7;
3061 for (i
= 0; i
< g
->num_edges
; i
++) {
3062 /* If we're changing state, AND
3063 * the previous state was a coloured line */
3064 if ((state
->lines
[i
] != (ds
->lines
[i
] & ~redraw_flag
)) &&
3065 ((ds
->lines
[i
] & ~redraw_flag
) != LINE_NO
)) {
3066 grid_edge
*e
= g
->edges
+ i
;
3067 int x1
= e
->dot1
->x
;
3068 int y1
= e
->dot1
->y
;
3069 int x2
= e
->dot2
->x
;
3070 int y2
= e
->dot2
->y
;
3071 int xmin
, xmax
, ymin
, ymax
;
3073 grid_to_screen(ds
, g
, x1
, y1
, &x1
, &y1
);
3074 grid_to_screen(ds
, g
, x2
, y2
, &x2
, &y2
);
3075 /* Allow extra margin for dots, and thickness of lines */
3076 xmin
= min(x1
, x2
) - 2;
3077 xmax
= max(x1
, x2
) + 2;
3078 ymin
= min(y1
, y2
) - 2;
3079 ymax
= max(y1
, y2
) + 2;
3080 /* For testing, I find it helpful to change COL_BACKGROUND
3081 * to COL_SATISFIED here. */
3082 draw_rect(dr
, xmin
, ymin
, xmax
- xmin
+ 1, ymax
- ymin
+ 1,
3084 draw_update(dr
, xmin
, ymin
, xmax
- xmin
+ 1, ymax
- ymin
+ 1);
3086 /* Mark nearby lines for redraw */
3087 for (j
= 0; j
< e
->dot1
->order
; j
++)
3088 ds
->lines
[e
->dot1
->edges
[j
] - g
->edges
] |= redraw_flag
;
3089 for (j
= 0; j
< e
->dot2
->order
; j
++)
3090 ds
->lines
[e
->dot2
->edges
[j
] - g
->edges
] |= redraw_flag
;
3091 /* Mark nearby clues for redraw. Use a value that is
3092 * neither TRUE nor FALSE for this. */
3094 ds
->clue_error
[e
->face1
- g
->faces
] = 2;
3096 ds
->clue_error
[e
->face2
- g
->faces
] = 2;
3101 /* Redraw clue colours if necessary */
3102 for (i
= 0; i
< g
->num_faces
; i
++) {
3103 grid_face
*f
= g
->faces
+ i
;
3104 int sides
= f
->order
;
3106 n
= state
->clues
[i
];
3110 c
[0] = CLUE2CHAR(n
);
3113 clue_mistake
= (face_order(state
, i
, LINE_YES
) > n
||
3114 face_order(state
, i
, LINE_NO
) > (sides
-n
));
3116 clue_satisfied
= (face_order(state
, i
, LINE_YES
) == n
&&
3117 face_order(state
, i
, LINE_NO
) == (sides
-n
));
3119 if (clue_mistake
!= ds
->clue_error
[i
]
3120 || clue_satisfied
!= ds
->clue_satisfied
[i
]) {
3122 face_text_pos(ds
, g
, f
, &x
, &y
);
3123 /* There seems to be a certain amount of trial-and-error
3124 * involved in working out the correct bounding-box for
3126 draw_rect(dr
, x
- ds
->tilesize
/4 - 1, y
- ds
->tilesize
/4 - 3,
3127 ds
->tilesize
/2 + 2, ds
->tilesize
/2 + 5,
3130 FONT_VARIABLE
, ds
->tilesize
/2,
3131 ALIGN_VCENTRE
| ALIGN_HCENTRE
,
3132 clue_mistake ? COL_MISTAKE
:
3133 clue_satisfied ? COL_SATISFIED
: COL_FOREGROUND
, c
);
3134 draw_update(dr
, x
- ds
->tilesize
/4 - 1, y
- ds
->tilesize
/4 - 3,
3135 ds
->tilesize
/2 + 2, ds
->tilesize
/2 + 5);
3137 ds
->clue_error
[i
] = clue_mistake
;
3138 ds
->clue_satisfied
[i
] = clue_satisfied
;
3140 /* Sometimes, the bounding-box encroaches into the surrounding
3141 * lines (particularly if the window is resized fairly small).
3142 * So redraw them. */
3143 for (j
= 0; j
< f
->order
; j
++)
3144 ds
->lines
[f
->edges
[j
] - g
->edges
] = -1;
3148 /* I've also had a request to colour lines red if they make a non-solution
3149 * loop, or if more than two lines go into any point. I think that would
3150 * be good some time. */
3153 for (i
= 0; i
< g
->num_edges
; i
++) {
3154 grid_edge
*e
= g
->edges
+ i
;
3156 int xmin
, ymin
, xmax
, ymax
;
3157 int need_draw
= (state
->lines
[i
] != ds
->lines
[i
]) ? TRUE
: FALSE
;
3158 if (flash_changed
&& (state
->lines
[i
] == LINE_YES
))
3161 need_draw
= TRUE
; /* draw everything at the start */
3162 ds
->lines
[i
] = state
->lines
[i
];
3165 if (state
->lines
[i
] == LINE_UNKNOWN
)
3166 line_colour
= COL_LINEUNKNOWN
;
3167 else if (state
->lines
[i
] == LINE_NO
)
3168 line_colour
= COL_BACKGROUND
;
3169 else if (ds
->flashing
)
3170 line_colour
= COL_HIGHLIGHT
;
3172 line_colour
= COL_FOREGROUND
;
3174 /* Convert from grid to screen coordinates */
3175 grid_to_screen(ds
, g
, e
->dot1
->x
, e
->dot1
->y
, &x1
, &y1
);
3176 grid_to_screen(ds
, g
, e
->dot2
->x
, e
->dot2
->y
, &x2
, &y2
);
3183 if (line_colour
!= COL_BACKGROUND
) {
3184 /* (dx, dy) points roughly from (x1, y1) to (x2, y2).
3185 * The line is then "fattened" in a (roughly) perpendicular
3186 * direction to create a thin rectangle. */
3187 int dx
= (x1
> x2
) ?
-1 : ((x1
< x2
) ?
1 : 0);
3188 int dy
= (y1
> y2
) ?
-1 : ((y1
< y2
) ?
1 : 0);
3195 draw_polygon(dr
, points
, 4, line_colour
, line_colour
);
3198 /* Draw dots at ends of the line */
3199 draw_circle(dr
, x1
, y1
, 2, COL_FOREGROUND
, COL_FOREGROUND
);
3200 draw_circle(dr
, x2
, y2
, 2, COL_FOREGROUND
, COL_FOREGROUND
);
3202 draw_update(dr
, xmin
-2, ymin
-2, xmax
- xmin
+ 4, ymax
- ymin
+ 4);
3207 for (i
= 0; i
< g
->num_dots
; i
++) {
3208 grid_dot
*d
= g
->dots
+ i
;
3210 grid_to_screen(ds
, g
, d
->x
, d
->y
, &x
, &y
);
3211 draw_circle(dr
, x
, y
, 2, COL_FOREGROUND
, COL_FOREGROUND
);
3217 static float game_flash_length(game_state
*oldstate
, game_state
*newstate
,
3218 int dir
, game_ui
*ui
)
3220 if (!oldstate
->solved
&& newstate
->solved
&&
3221 !oldstate
->cheated
&& !newstate
->cheated
) {
3228 static void game_print_size(game_params
*params
, float *x
, float *y
)
3233 * I'll use 7mm "squares" by default.
3235 game_compute_size(params
, 700, &pw
, &ph
);
3240 static void game_print(drawing
*dr
, game_state
*state
, int tilesize
)
3242 int ink
= print_mono_colour(dr
, 0);
3244 game_drawstate ads
, *ds
= &ads
;
3245 grid
*g
= state
->game_grid
;
3247 game_set_size(dr
, ds
, NULL
, tilesize
);
3249 for (i
= 0; i
< g
->num_dots
; i
++) {
3251 grid_to_screen(ds
, g
, g
->dots
[i
].x
, g
->dots
[i
].y
, &x
, &y
);
3252 draw_circle(dr
, x
, y
, ds
->tilesize
/ 15, ink
, ink
);
3258 for (i
= 0; i
< g
->num_faces
; i
++) {
3259 grid_face
*f
= g
->faces
+ i
;
3260 int clue
= state
->clues
[i
];
3264 c
[0] = CLUE2CHAR(clue
);
3266 face_text_pos(ds
, g
, f
, &x
, &y
);
3268 FONT_VARIABLE
, ds
->tilesize
/ 2,
3269 ALIGN_VCENTRE
| ALIGN_HCENTRE
, ink
, c
);
3276 for (i
= 0; i
< g
->num_edges
; i
++) {
3277 int thickness
= (state
->lines
[i
] == LINE_YES
) ?
30 : 150;
3278 grid_edge
*e
= g
->edges
+ i
;
3280 grid_to_screen(ds
, g
, e
->dot1
->x
, e
->dot1
->y
, &x1
, &y1
);
3281 grid_to_screen(ds
, g
, e
->dot2
->x
, e
->dot2
->y
, &x2
, &y2
);
3282 if (state
->lines
[i
] == LINE_YES
)
3284 /* (dx, dy) points from (x1, y1) to (x2, y2).
3285 * The line is then "fattened" in a perpendicular
3286 * direction to create a thin rectangle. */
3287 double d
= sqrt(SQ((double)x1
- x2
) + SQ((double)y1
- y2
));
3288 double dx
= (x2
- x1
) / d
;
3289 double dy
= (y2
- y1
) / d
;
3292 dx
= (dx
* ds
->tilesize
) / thickness
;
3293 dy
= (dy
* ds
->tilesize
) / thickness
;
3294 points
[0] = x1
+ dy
;
3295 points
[1] = y1
- dx
;
3296 points
[2] = x1
- dy
;
3297 points
[3] = y1
+ dx
;
3298 points
[4] = x2
- dy
;
3299 points
[5] = y2
+ dx
;
3300 points
[6] = x2
+ dy
;
3301 points
[7] = y2
- dx
;
3302 draw_polygon(dr
, points
, 4, ink
, ink
);
3306 /* Draw a dotted line */
3309 for (j
= 1; j
< divisions
; j
++) {
3310 /* Weighted average */
3311 int x
= (x1
* (divisions
-j
) + x2
* j
) / divisions
;
3312 int y
= (y1
* (divisions
-j
) + y2
* j
) / divisions
;
3313 draw_circle(dr
, x
, y
, ds
->tilesize
/ thickness
, ink
, ink
);
3320 #define thegame loopy
3323 const struct game thegame
= {
3324 "Loopy", "games.loopy", "loopy",
3331 TRUE
, game_configure
, custom_params
,
3339 TRUE
, game_can_format_as_text_now
, game_text_format
,
3347 PREFERRED_TILE_SIZE
, game_compute_size
, game_set_size
,
3350 game_free_drawstate
,
3354 TRUE
, FALSE
, game_print_size
, game_print
,
3355 FALSE
/* wants_statusbar */,
3356 FALSE
, game_timing_state
,
3357 0, /* mouse_priorities */