4 * An implementation of the Nikoli game 'Loop the loop'.
5 * (c) Mike Pinna, 2005, 2006
6 * Substantially rewritten to allowing for more general types of grid.
7 * (c) Lambros Lambrou 2008
9 * vim: set shiftwidth=4 :set textwidth=80:
13 * Possible future solver enhancements:
15 * - There's an interesting deductive technique which makes use
16 * of topology rather than just graph theory. Each _face_ in
17 * the grid is either inside or outside the loop; you can tell
18 * that two faces are on the same side of the loop if they're
19 * separated by a LINE_NO (or, more generally, by a path
20 * crossing no LINE_UNKNOWNs and an even number of LINE_YESes),
21 * and on the opposite side of the loop if they're separated by
22 * a LINE_YES (or an odd number of LINE_YESes and no
23 * LINE_UNKNOWNs). Oh, and any face separated from the outside
24 * of the grid by a LINE_YES or a LINE_NO is on the inside or
25 * outside respectively. So if you can track this for all
26 * faces, you figure out the state of the line between a pair
27 * once their relative insideness is known.
28 * + The way I envisage this working is simply to keep an edsf
29 * of all _faces_, which indicates whether they're on
30 * opposite sides of the loop from one another. We also
31 * include a special entry in the edsf for the infinite
33 * + So, the simple way to do this is to just go through the
34 * edges: every time we see an edge in a state other than
35 * LINE_UNKNOWN which separates two faces that aren't in the
36 * same edsf class, we can rectify that by merging the
37 * classes. Then, conversely, an edge in LINE_UNKNOWN state
38 * which separates two faces that _are_ in the same edsf
39 * class can immediately have its state determined.
40 * + But you can go one better, if you're prepared to loop
41 * over all _pairs_ of edges. Suppose we have edges A and B,
42 * which respectively separate faces A1,A2 and B1,B2.
43 * Suppose that A,B are in the same edge-edsf class and that
44 * A1,B1 (wlog) are in the same face-edsf class; then we can
45 * immediately place A2,B2 into the same face-edsf class (as
46 * each other, not as A1 and A2) one way round or the other.
47 * And conversely again, if A1,B1 are in the same face-edsf
48 * class and so are A2,B2, then we can put A,B into the same
50 * * Of course, this deduction requires a quadratic-time
51 * loop over all pairs of edges in the grid, so it should
52 * be reserved until there's nothing easier left to be
55 * - The generalised grid support has made me (SGT) notice a
56 * possible extension to the loop-avoidance code. When you have
57 * a path of connected edges such that no other edges at all
58 * are incident on any vertex in the middle of the path - or,
59 * alternatively, such that any such edges are already known to
60 * be LINE_NO - then you know those edges are either all
61 * LINE_YES or all LINE_NO. Hence you can mentally merge the
62 * entire path into a single long curly edge for the purposes
63 * of loop avoidance, and look directly at whether or not the
64 * extreme endpoints of the path are connected by some other
65 * route. I find this coming up fairly often when I play on the
66 * octagonal grid setting, so it might be worth implementing in
69 * - (Just a speed optimisation.) Consider some todo list queue where every
70 * time we modify something we mark it for consideration by other bits of
71 * the solver, to save iteration over things that have already been done.
85 /* Debugging options */
93 /* ----------------------------------------------------------------------
94 * Struct, enum and function declarations
110 /* Put -1 in a face that doesn't get a clue */
113 /* Array of line states, to store whether each line is
114 * YES, NO or UNKNOWN */
117 unsigned char *line_errors
;
122 /* Used in game_text_format(), so that it knows what type of
123 * grid it's trying to render as ASCII text. */
128 SOLVER_SOLVED
, /* This is the only solution the solver could find */
129 SOLVER_MISTAKE
, /* This is definitely not a solution */
130 SOLVER_AMBIGUOUS
, /* This _might_ be an ambiguous solution */
131 SOLVER_INCOMPLETE
/* This may be a partial solution */
134 /* ------ Solver state ------ */
135 typedef struct normal
{
136 /* For each dline, store a bitmask for whether we know:
137 * (bit 0) at least one is YES
138 * (bit 1) at most one is YES */
142 typedef struct hard
{
146 typedef struct solver_state
{
148 enum solver_status solver_status
;
149 /* NB looplen is the number of dots that are joined together at a point, ie a
150 * looplen of 1 means there are no lines to a particular dot */
156 char *face_yes_count
;
158 char *dot_solved
, *face_solved
;
161 normal_mode_state
*normal
;
162 hard_mode_state
*hard
;
166 * Difficulty levels. I do some macro ickery here to ensure that my
167 * enum and the various forms of my name list always match up.
170 #define DIFFLIST(A) \
171 A(EASY,Easy,e,easy_mode_deductions) \
172 A(NORMAL,Normal,n,normal_mode_deductions) \
173 A(HARD,Hard,h,hard_mode_deductions)
174 #define ENUM(upper,title,lower,fn) DIFF_ ## upper,
175 #define TITLE(upper,title,lower,fn) #title,
176 #define ENCODE(upper,title,lower,fn) #lower
177 #define CONFIG(upper,title,lower,fn) ":" #title
178 #define SOLVER_FN_DECL(upper,title,lower,fn) static int fn(solver_state *);
179 #define SOLVER_FN(upper,title,lower,fn) &fn,
180 enum { DIFFLIST(ENUM
) DIFF_MAX
};
181 static char const *const diffnames
[] = { DIFFLIST(TITLE
) };
182 static char const diffchars
[] = DIFFLIST(ENCODE
);
183 #define DIFFCONFIG DIFFLIST(CONFIG)
184 DIFFLIST(SOLVER_FN_DECL
)
185 static int (*(solver_fns
[]))(solver_state
*) = { DIFFLIST(SOLVER_FN
) };
192 /* Grid generation is expensive, so keep a (ref-counted) reference to the
193 * grid for these parameters, and only generate when required. */
197 /* line_drawstate is the same as line_state, but with the extra ERROR
198 * possibility. The drawing code copies line_state to line_drawstate,
199 * except in the case that the line is an error. */
200 enum line_state
{ LINE_YES
, LINE_UNKNOWN
, LINE_NO
};
201 enum line_drawstate
{ DS_LINE_YES
, DS_LINE_UNKNOWN
,
202 DS_LINE_NO
, DS_LINE_ERROR
};
204 #define OPP(line_state) \
208 struct game_drawstate
{
214 char *clue_satisfied
;
217 static char *validate_desc(game_params
*params
, char *desc
);
218 static int dot_order(const game_state
* state
, int i
, char line_type
);
219 static int face_order(const game_state
* state
, int i
, char line_type
);
220 static solver_state
*solve_game_rec(const solver_state
*sstate
,
224 static void check_caches(const solver_state
* sstate
);
226 #define check_caches(s)
229 /* ------- List of grid generators ------- */
230 #define GRIDLIST(A) \
231 A(Squares,grid_new_square) \
232 A(Triangular,grid_new_triangular) \
233 A(Honeycomb,grid_new_honeycomb) \
234 A(Snub-Square,grid_new_snubsquare) \
235 A(Cairo,grid_new_cairo) \
236 A(Great-Hexagonal,grid_new_greathexagonal) \
237 A(Octagonal,grid_new_octagonal) \
238 A(Kites,grid_new_kites)
240 #define GRID_NAME(title,fn) #title,
241 #define GRID_CONFIG(title,fn) ":" #title
242 #define GRID_FN(title,fn) &fn,
243 static char const *const gridnames
[] = { GRIDLIST(GRID_NAME
) };
244 #define GRID_CONFIGS GRIDLIST(GRID_CONFIG)
245 static grid
* (*(grid_fns
[]))(int w
, int h
) = { GRIDLIST(GRID_FN
) };
246 #define NUM_GRID_TYPES (sizeof(grid_fns) / sizeof(grid_fns[0]))
248 /* Generates a (dynamically allocated) new grid, according to the
249 * type and size requested in params. Does nothing if the grid is already
250 * generated. The allocated grid is owned by the params object, and will be
251 * freed in free_params(). */
252 static void params_generate_grid(game_params
*params
)
254 if (!params
->game_grid
) {
255 params
->game_grid
= grid_fns
[params
->type
](params
->w
, params
->h
);
259 /* ----------------------------------------------------------------------
263 /* General constants */
264 #define PREFERRED_TILE_SIZE 32
265 #define BORDER(tilesize) ((tilesize) / 2)
266 #define FLASH_TIME 0.5F
268 #define BIT_SET(field, bit) ((field) & (1<<(bit)))
270 #define SET_BIT(field, bit) (BIT_SET(field, bit) ? FALSE : \
271 ((field) |= (1<<(bit)), TRUE))
273 #define CLEAR_BIT(field, bit) (BIT_SET(field, bit) ? \
274 ((field) &= ~(1<<(bit)), TRUE) : FALSE)
276 #define CLUE2CHAR(c) \
277 ((c < 0) ? ' ' : c + '0')
279 /* ----------------------------------------------------------------------
280 * General struct manipulation and other straightforward code
283 static game_state
*dup_game(game_state
*state
)
285 game_state
*ret
= snew(game_state
);
287 ret
->game_grid
= state
->game_grid
;
288 ret
->game_grid
->refcount
++;
290 ret
->solved
= state
->solved
;
291 ret
->cheated
= state
->cheated
;
293 ret
->clues
= snewn(state
->game_grid
->num_faces
, signed char);
294 memcpy(ret
->clues
, state
->clues
, state
->game_grid
->num_faces
);
296 ret
->lines
= snewn(state
->game_grid
->num_edges
, char);
297 memcpy(ret
->lines
, state
->lines
, state
->game_grid
->num_edges
);
299 ret
->line_errors
= snewn(state
->game_grid
->num_edges
, unsigned char);
300 memcpy(ret
->line_errors
, state
->line_errors
, state
->game_grid
->num_edges
);
302 ret
->grid_type
= state
->grid_type
;
306 static void free_game(game_state
*state
)
309 grid_free(state
->game_grid
);
312 sfree(state
->line_errors
);
317 static solver_state
*new_solver_state(game_state
*state
, int diff
) {
319 int num_dots
= state
->game_grid
->num_dots
;
320 int num_faces
= state
->game_grid
->num_faces
;
321 int num_edges
= state
->game_grid
->num_edges
;
322 solver_state
*ret
= snew(solver_state
);
324 ret
->state
= dup_game(state
);
326 ret
->solver_status
= SOLVER_INCOMPLETE
;
328 ret
->dotdsf
= snew_dsf(num_dots
);
329 ret
->looplen
= snewn(num_dots
, int);
331 for (i
= 0; i
< num_dots
; i
++) {
335 ret
->dot_solved
= snewn(num_dots
, char);
336 ret
->face_solved
= snewn(num_faces
, char);
337 memset(ret
->dot_solved
, FALSE
, num_dots
);
338 memset(ret
->face_solved
, FALSE
, num_faces
);
340 ret
->dot_yes_count
= snewn(num_dots
, char);
341 memset(ret
->dot_yes_count
, 0, num_dots
);
342 ret
->dot_no_count
= snewn(num_dots
, char);
343 memset(ret
->dot_no_count
, 0, num_dots
);
344 ret
->face_yes_count
= snewn(num_faces
, char);
345 memset(ret
->face_yes_count
, 0, num_faces
);
346 ret
->face_no_count
= snewn(num_faces
, char);
347 memset(ret
->face_no_count
, 0, num_faces
);
349 if (diff
< DIFF_NORMAL
) {
352 ret
->normal
= snew(normal_mode_state
);
353 ret
->normal
->dlines
= snewn(2*num_edges
, char);
354 memset(ret
->normal
->dlines
, 0, 2*num_edges
);
357 if (diff
< DIFF_HARD
) {
360 ret
->hard
= snew(hard_mode_state
);
361 ret
->hard
->linedsf
= snew_dsf(state
->game_grid
->num_edges
);
367 static void free_solver_state(solver_state
*sstate
) {
369 free_game(sstate
->state
);
370 sfree(sstate
->dotdsf
);
371 sfree(sstate
->looplen
);
372 sfree(sstate
->dot_solved
);
373 sfree(sstate
->face_solved
);
374 sfree(sstate
->dot_yes_count
);
375 sfree(sstate
->dot_no_count
);
376 sfree(sstate
->face_yes_count
);
377 sfree(sstate
->face_no_count
);
379 if (sstate
->normal
) {
380 sfree(sstate
->normal
->dlines
);
381 sfree(sstate
->normal
);
385 sfree(sstate
->hard
->linedsf
);
393 static solver_state
*dup_solver_state(const solver_state
*sstate
) {
394 game_state
*state
= sstate
->state
;
395 int num_dots
= state
->game_grid
->num_dots
;
396 int num_faces
= state
->game_grid
->num_faces
;
397 int num_edges
= state
->game_grid
->num_edges
;
398 solver_state
*ret
= snew(solver_state
);
400 ret
->state
= state
= dup_game(sstate
->state
);
402 ret
->solver_status
= sstate
->solver_status
;
404 ret
->dotdsf
= snewn(num_dots
, int);
405 ret
->looplen
= snewn(num_dots
, int);
406 memcpy(ret
->dotdsf
, sstate
->dotdsf
,
407 num_dots
* sizeof(int));
408 memcpy(ret
->looplen
, sstate
->looplen
,
409 num_dots
* sizeof(int));
411 ret
->dot_solved
= snewn(num_dots
, char);
412 ret
->face_solved
= snewn(num_faces
, char);
413 memcpy(ret
->dot_solved
, sstate
->dot_solved
, num_dots
);
414 memcpy(ret
->face_solved
, sstate
->face_solved
, num_faces
);
416 ret
->dot_yes_count
= snewn(num_dots
, char);
417 memcpy(ret
->dot_yes_count
, sstate
->dot_yes_count
, num_dots
);
418 ret
->dot_no_count
= snewn(num_dots
, char);
419 memcpy(ret
->dot_no_count
, sstate
->dot_no_count
, num_dots
);
421 ret
->face_yes_count
= snewn(num_faces
, char);
422 memcpy(ret
->face_yes_count
, sstate
->face_yes_count
, num_faces
);
423 ret
->face_no_count
= snewn(num_faces
, char);
424 memcpy(ret
->face_no_count
, sstate
->face_no_count
, num_faces
);
426 if (sstate
->normal
) {
427 ret
->normal
= snew(normal_mode_state
);
428 ret
->normal
->dlines
= snewn(2*num_edges
, char);
429 memcpy(ret
->normal
->dlines
, sstate
->normal
->dlines
,
436 ret
->hard
= snew(hard_mode_state
);
437 ret
->hard
->linedsf
= snewn(num_edges
, int);
438 memcpy(ret
->hard
->linedsf
, sstate
->hard
->linedsf
,
439 num_edges
* sizeof(int));
447 static game_params
*default_params(void)
449 game_params
*ret
= snew(game_params
);
458 ret
->diff
= DIFF_EASY
;
461 ret
->game_grid
= NULL
;
466 static game_params
*dup_params(game_params
*params
)
468 game_params
*ret
= snew(game_params
);
470 *ret
= *params
; /* structure copy */
471 if (ret
->game_grid
) {
472 ret
->game_grid
->refcount
++;
477 static const game_params presets
[] = {
479 { 7, 7, DIFF_EASY
, 0, NULL
},
480 { 7, 7, DIFF_NORMAL
, 0, NULL
},
481 { 7, 7, DIFF_HARD
, 0, NULL
},
482 { 7, 7, DIFF_HARD
, 1, NULL
},
483 { 7, 7, DIFF_HARD
, 2, NULL
},
484 { 5, 5, DIFF_HARD
, 3, NULL
},
485 { 7, 7, DIFF_HARD
, 4, NULL
},
486 { 5, 4, DIFF_HARD
, 5, NULL
},
487 { 5, 5, DIFF_HARD
, 6, NULL
},
488 { 5, 5, DIFF_HARD
, 7, NULL
},
490 { 7, 7, DIFF_EASY
, 0, NULL
},
491 { 10, 10, DIFF_EASY
, 0, NULL
},
492 { 7, 7, DIFF_NORMAL
, 0, NULL
},
493 { 10, 10, DIFF_NORMAL
, 0, NULL
},
494 { 7, 7, DIFF_HARD
, 0, NULL
},
495 { 10, 10, DIFF_HARD
, 0, NULL
},
496 { 10, 10, DIFF_HARD
, 1, NULL
},
497 { 12, 10, DIFF_HARD
, 2, NULL
},
498 { 7, 7, DIFF_HARD
, 3, NULL
},
499 { 9, 9, DIFF_HARD
, 4, NULL
},
500 { 5, 4, DIFF_HARD
, 5, NULL
},
501 { 7, 7, DIFF_HARD
, 6, NULL
},
502 { 5, 5, DIFF_HARD
, 7, NULL
},
506 static int game_fetch_preset(int i
, char **name
, game_params
**params
)
511 if (i
< 0 || i
>= lenof(presets
))
514 tmppar
= snew(game_params
);
515 *tmppar
= presets
[i
];
517 sprintf(buf
, "%dx%d %s - %s", tmppar
->h
, tmppar
->w
,
518 gridnames
[tmppar
->type
], diffnames
[tmppar
->diff
]);
524 static void free_params(game_params
*params
)
526 if (params
->game_grid
) {
527 grid_free(params
->game_grid
);
532 static void decode_params(game_params
*params
, char const *string
)
534 if (params
->game_grid
) {
535 grid_free(params
->game_grid
);
536 params
->game_grid
= NULL
;
538 params
->h
= params
->w
= atoi(string
);
539 params
->diff
= DIFF_EASY
;
540 while (*string
&& isdigit((unsigned char)*string
)) string
++;
541 if (*string
== 'x') {
543 params
->h
= atoi(string
);
544 while (*string
&& isdigit((unsigned char)*string
)) string
++;
546 if (*string
== 't') {
548 params
->type
= atoi(string
);
549 while (*string
&& isdigit((unsigned char)*string
)) string
++;
551 if (*string
== 'd') {
554 for (i
= 0; i
< DIFF_MAX
; i
++)
555 if (*string
== diffchars
[i
])
557 if (*string
) string
++;
561 static char *encode_params(game_params
*params
, int full
)
564 sprintf(str
, "%dx%dt%d", params
->w
, params
->h
, params
->type
);
566 sprintf(str
+ strlen(str
), "d%c", diffchars
[params
->diff
]);
570 static config_item
*game_configure(game_params
*params
)
575 ret
= snewn(5, config_item
);
577 ret
[0].name
= "Width";
578 ret
[0].type
= C_STRING
;
579 sprintf(buf
, "%d", params
->w
);
580 ret
[0].sval
= dupstr(buf
);
583 ret
[1].name
= "Height";
584 ret
[1].type
= C_STRING
;
585 sprintf(buf
, "%d", params
->h
);
586 ret
[1].sval
= dupstr(buf
);
589 ret
[2].name
= "Grid type";
590 ret
[2].type
= C_CHOICES
;
591 ret
[2].sval
= GRID_CONFIGS
;
592 ret
[2].ival
= params
->type
;
594 ret
[3].name
= "Difficulty";
595 ret
[3].type
= C_CHOICES
;
596 ret
[3].sval
= DIFFCONFIG
;
597 ret
[3].ival
= params
->diff
;
607 static game_params
*custom_params(config_item
*cfg
)
609 game_params
*ret
= snew(game_params
);
611 ret
->w
= atoi(cfg
[0].sval
);
612 ret
->h
= atoi(cfg
[1].sval
);
613 ret
->type
= cfg
[2].ival
;
614 ret
->diff
= cfg
[3].ival
;
616 ret
->game_grid
= NULL
;
620 static char *validate_params(game_params
*params
, int full
)
622 if (params
->w
< 3 || params
->h
< 3)
623 return "Width and height must both be at least 3";
624 if (params
->type
< 0 || params
->type
>= NUM_GRID_TYPES
)
625 return "Illegal grid type";
628 * This shouldn't be able to happen at all, since decode_params
629 * and custom_params will never generate anything that isn't
632 assert(params
->diff
< DIFF_MAX
);
637 /* Returns a newly allocated string describing the current puzzle */
638 static char *state_to_text(const game_state
*state
)
640 grid
*g
= state
->game_grid
;
642 int num_faces
= g
->num_faces
;
643 char *description
= snewn(num_faces
+ 1, char);
644 char *dp
= description
;
648 for (i
= 0; i
< num_faces
; i
++) {
649 if (state
->clues
[i
] < 0) {
650 if (empty_count
> 25) {
651 dp
+= sprintf(dp
, "%c", (int)(empty_count
+ 'a' - 1));
657 dp
+= sprintf(dp
, "%c", (int)(empty_count
+ 'a' - 1));
660 dp
+= sprintf(dp
, "%c", (int)CLUE2CHAR(state
->clues
[i
]));
665 dp
+= sprintf(dp
, "%c", (int)(empty_count
+ 'a' - 1));
667 retval
= dupstr(description
);
673 /* We require that the params pass the test in validate_params and that the
674 * description fills the entire game area */
675 static char *validate_desc(game_params
*params
, char *desc
)
679 params_generate_grid(params
);
680 g
= params
->game_grid
;
682 for (; *desc
; ++desc
) {
683 if (*desc
>= '0' && *desc
<= '9') {
688 count
+= *desc
- 'a' + 1;
691 return "Unknown character in description";
694 if (count
< g
->num_faces
)
695 return "Description too short for board size";
696 if (count
> g
->num_faces
)
697 return "Description too long for board size";
702 /* Sums the lengths of the numbers in range [0,n) */
703 /* See equivalent function in solo.c for justification of this. */
704 static int len_0_to_n(int n
)
706 int len
= 1; /* Counting 0 as a bit of a special case */
709 for (i
= 1; i
< n
; i
*= 10) {
710 len
+= max(n
- i
, 0);
716 static char *encode_solve_move(const game_state
*state
)
721 int num_edges
= state
->game_grid
->num_edges
;
723 /* This is going to return a string representing the moves needed to set
724 * every line in a grid to be the same as the ones in 'state'. The exact
725 * length of this string is predictable. */
727 len
= 1; /* Count the 'S' prefix */
728 /* Numbers in all lines */
729 len
+= len_0_to_n(num_edges
);
730 /* For each line we also have a letter */
733 ret
= snewn(len
+ 1, char);
736 p
+= sprintf(p
, "S");
738 for (i
= 0; i
< num_edges
; i
++) {
739 switch (state
->lines
[i
]) {
741 p
+= sprintf(p
, "%dy", i
);
744 p
+= sprintf(p
, "%dn", i
);
749 /* No point in doing sums like that if they're going to be wrong */
750 assert(strlen(ret
) <= (size_t)len
);
754 static game_ui
*new_ui(game_state
*state
)
759 static void free_ui(game_ui
*ui
)
763 static char *encode_ui(game_ui
*ui
)
768 static void decode_ui(game_ui
*ui
, char *encoding
)
772 static void game_changed_state(game_ui
*ui
, game_state
*oldstate
,
773 game_state
*newstate
)
777 static void game_compute_size(game_params
*params
, int tilesize
,
781 int grid_width
, grid_height
, rendered_width
, rendered_height
;
783 params_generate_grid(params
);
784 g
= params
->game_grid
;
785 grid_width
= g
->highest_x
- g
->lowest_x
;
786 grid_height
= g
->highest_y
- g
->lowest_y
;
787 /* multiply first to minimise rounding error on integer division */
788 rendered_width
= grid_width
* tilesize
/ g
->tilesize
;
789 rendered_height
= grid_height
* tilesize
/ g
->tilesize
;
790 *x
= rendered_width
+ 2 * BORDER(tilesize
) + 1;
791 *y
= rendered_height
+ 2 * BORDER(tilesize
) + 1;
794 static void game_set_size(drawing
*dr
, game_drawstate
*ds
,
795 game_params
*params
, int tilesize
)
797 ds
->tilesize
= tilesize
;
800 static float *game_colours(frontend
*fe
, int *ncolours
)
802 float *ret
= snewn(4 * NCOLOURS
, float);
804 frontend_default_colour(fe
, &ret
[COL_BACKGROUND
* 3]);
806 ret
[COL_FOREGROUND
* 3 + 0] = 0.0F
;
807 ret
[COL_FOREGROUND
* 3 + 1] = 0.0F
;
808 ret
[COL_FOREGROUND
* 3 + 2] = 0.0F
;
810 ret
[COL_LINEUNKNOWN
* 3 + 0] = 0.8F
;
811 ret
[COL_LINEUNKNOWN
* 3 + 1] = 0.8F
;
812 ret
[COL_LINEUNKNOWN
* 3 + 2] = 0.0F
;
814 ret
[COL_HIGHLIGHT
* 3 + 0] = 1.0F
;
815 ret
[COL_HIGHLIGHT
* 3 + 1] = 1.0F
;
816 ret
[COL_HIGHLIGHT
* 3 + 2] = 1.0F
;
818 ret
[COL_MISTAKE
* 3 + 0] = 1.0F
;
819 ret
[COL_MISTAKE
* 3 + 1] = 0.0F
;
820 ret
[COL_MISTAKE
* 3 + 2] = 0.0F
;
822 ret
[COL_SATISFIED
* 3 + 0] = 0.0F
;
823 ret
[COL_SATISFIED
* 3 + 1] = 0.0F
;
824 ret
[COL_SATISFIED
* 3 + 2] = 0.0F
;
826 *ncolours
= NCOLOURS
;
830 static game_drawstate
*game_new_drawstate(drawing
*dr
, game_state
*state
)
832 struct game_drawstate
*ds
= snew(struct game_drawstate
);
833 int num_faces
= state
->game_grid
->num_faces
;
834 int num_edges
= state
->game_grid
->num_edges
;
838 ds
->lines
= snewn(num_edges
, char);
839 ds
->clue_error
= snewn(num_faces
, char);
840 ds
->clue_satisfied
= snewn(num_faces
, char);
843 memset(ds
->lines
, LINE_UNKNOWN
, num_edges
);
844 memset(ds
->clue_error
, 0, num_faces
);
845 memset(ds
->clue_satisfied
, 0, num_faces
);
850 static void game_free_drawstate(drawing
*dr
, game_drawstate
*ds
)
852 sfree(ds
->clue_error
);
853 sfree(ds
->clue_satisfied
);
858 static int game_timing_state(game_state
*state
, game_ui
*ui
)
863 static float game_anim_length(game_state
*oldstate
, game_state
*newstate
,
864 int dir
, game_ui
*ui
)
869 static int game_can_format_as_text_now(game_params
*params
)
871 if (params
->type
!= 0)
876 static char *game_text_format(game_state
*state
)
882 grid
*g
= state
->game_grid
;
885 assert(state
->grid_type
== 0);
887 /* Work out the basic size unit */
888 f
= g
->faces
; /* first face */
889 assert(f
->order
== 4);
890 /* The dots are ordered clockwise, so the two opposite
891 * corners are guaranteed to span the square */
892 cell_size
= abs(f
->dots
[0]->x
- f
->dots
[2]->x
);
894 w
= (g
->highest_x
- g
->lowest_x
) / cell_size
;
895 h
= (g
->highest_y
- g
->lowest_y
) / cell_size
;
897 /* Create a blank "canvas" to "draw" on */
900 ret
= snewn(W
* H
+ 1, char);
901 for (y
= 0; y
< H
; y
++) {
902 for (x
= 0; x
< W
-1; x
++) {
905 ret
[y
*W
+ W
-1] = '\n';
909 /* Fill in edge info */
910 for (i
= 0; i
< g
->num_edges
; i
++) {
911 grid_edge
*e
= g
->edges
+ i
;
912 /* Cell coordinates, from (0,0) to (w-1,h-1) */
913 int x1
= (e
->dot1
->x
- g
->lowest_x
) / cell_size
;
914 int x2
= (e
->dot2
->x
- g
->lowest_x
) / cell_size
;
915 int y1
= (e
->dot1
->y
- g
->lowest_y
) / cell_size
;
916 int y2
= (e
->dot2
->y
- g
->lowest_y
) / cell_size
;
917 /* Midpoint, in canvas coordinates (canvas coordinates are just twice
918 * cell coordinates) */
921 switch (state
->lines
[i
]) {
923 ret
[y
*W
+ x
] = (y1
== y2
) ?
'-' : '|';
929 break; /* already a space */
931 assert(!"Illegal line state");
936 for (i
= 0; i
< g
->num_faces
; i
++) {
940 assert(f
->order
== 4);
941 /* Cell coordinates, from (0,0) to (w-1,h-1) */
942 x1
= (f
->dots
[0]->x
- g
->lowest_x
) / cell_size
;
943 x2
= (f
->dots
[2]->x
- g
->lowest_x
) / cell_size
;
944 y1
= (f
->dots
[0]->y
- g
->lowest_y
) / cell_size
;
945 y2
= (f
->dots
[2]->y
- g
->lowest_y
) / cell_size
;
946 /* Midpoint, in canvas coordinates */
949 ret
[y
*W
+ x
] = CLUE2CHAR(state
->clues
[i
]);
954 /* ----------------------------------------------------------------------
959 static void check_caches(const solver_state
* sstate
)
962 const game_state
*state
= sstate
->state
;
963 const grid
*g
= state
->game_grid
;
965 for (i
= 0; i
< g
->num_dots
; i
++) {
966 assert(dot_order(state
, i
, LINE_YES
) == sstate
->dot_yes_count
[i
]);
967 assert(dot_order(state
, i
, LINE_NO
) == sstate
->dot_no_count
[i
]);
970 for (i
= 0; i
< g
->num_faces
; i
++) {
971 assert(face_order(state
, i
, LINE_YES
) == sstate
->face_yes_count
[i
]);
972 assert(face_order(state
, i
, LINE_NO
) == sstate
->face_no_count
[i
]);
977 #define check_caches(s) \
979 fprintf(stderr, "check_caches at line %d\n", __LINE__); \
983 #endif /* DEBUG_CACHES */
985 /* ----------------------------------------------------------------------
986 * Solver utility functions
989 /* Sets the line (with index i) to the new state 'line_new', and updates
990 * the cached counts of any affected faces and dots.
991 * Returns TRUE if this actually changed the line's state. */
992 static int solver_set_line(solver_state
*sstate
, int i
,
993 enum line_state line_new
999 game_state
*state
= sstate
->state
;
1003 assert(line_new
!= LINE_UNKNOWN
);
1005 check_caches(sstate
);
1007 if (state
->lines
[i
] == line_new
) {
1008 return FALSE
; /* nothing changed */
1010 state
->lines
[i
] = line_new
;
1013 fprintf(stderr
, "solver: set line [%d] to %s (%s)\n",
1014 i
, line_new
== LINE_YES ?
"YES" : "NO",
1018 g
= state
->game_grid
;
1021 /* Update the cache for both dots and both faces affected by this. */
1022 if (line_new
== LINE_YES
) {
1023 sstate
->dot_yes_count
[e
->dot1
- g
->dots
]++;
1024 sstate
->dot_yes_count
[e
->dot2
- g
->dots
]++;
1026 sstate
->face_yes_count
[e
->face1
- g
->faces
]++;
1029 sstate
->face_yes_count
[e
->face2
- g
->faces
]++;
1032 sstate
->dot_no_count
[e
->dot1
- g
->dots
]++;
1033 sstate
->dot_no_count
[e
->dot2
- g
->dots
]++;
1035 sstate
->face_no_count
[e
->face1
- g
->faces
]++;
1038 sstate
->face_no_count
[e
->face2
- g
->faces
]++;
1042 check_caches(sstate
);
1047 #define solver_set_line(a, b, c) \
1048 solver_set_line(a, b, c, __FUNCTION__)
1052 * Merge two dots due to the existence of an edge between them.
1053 * Updates the dsf tracking equivalence classes, and keeps track of
1054 * the length of path each dot is currently a part of.
1055 * Returns TRUE if the dots were already linked, ie if they are part of a
1056 * closed loop, and false otherwise.
1058 static int merge_dots(solver_state
*sstate
, int edge_index
)
1061 grid
*g
= sstate
->state
->game_grid
;
1062 grid_edge
*e
= g
->edges
+ edge_index
;
1064 i
= e
->dot1
- g
->dots
;
1065 j
= e
->dot2
- g
->dots
;
1067 i
= dsf_canonify(sstate
->dotdsf
, i
);
1068 j
= dsf_canonify(sstate
->dotdsf
, j
);
1073 len
= sstate
->looplen
[i
] + sstate
->looplen
[j
];
1074 dsf_merge(sstate
->dotdsf
, i
, j
);
1075 i
= dsf_canonify(sstate
->dotdsf
, i
);
1076 sstate
->looplen
[i
] = len
;
1081 /* Merge two lines because the solver has deduced that they must be either
1082 * identical or opposite. Returns TRUE if this is new information, otherwise
1084 static int merge_lines(solver_state
*sstate
, int i
, int j
, int inverse
1086 , const char *reason
1092 assert(i
< sstate
->state
->game_grid
->num_edges
);
1093 assert(j
< sstate
->state
->game_grid
->num_edges
);
1095 i
= edsf_canonify(sstate
->hard
->linedsf
, i
, &inv_tmp
);
1097 j
= edsf_canonify(sstate
->hard
->linedsf
, j
, &inv_tmp
);
1100 edsf_merge(sstate
->hard
->linedsf
, i
, j
, inverse
);
1104 fprintf(stderr
, "%s [%d] [%d] %s(%s)\n",
1106 inverse ?
"inverse " : "", reason
);
1113 #define merge_lines(a, b, c, d) \
1114 merge_lines(a, b, c, d, __FUNCTION__)
1117 /* Count the number of lines of a particular type currently going into the
1119 static int dot_order(const game_state
* state
, int dot
, char line_type
)
1122 grid
*g
= state
->game_grid
;
1123 grid_dot
*d
= g
->dots
+ dot
;
1126 for (i
= 0; i
< d
->order
; i
++) {
1127 grid_edge
*e
= d
->edges
[i
];
1128 if (state
->lines
[e
- g
->edges
] == line_type
)
1134 /* Count the number of lines of a particular type currently surrounding the
1136 static int face_order(const game_state
* state
, int face
, char line_type
)
1139 grid
*g
= state
->game_grid
;
1140 grid_face
*f
= g
->faces
+ face
;
1143 for (i
= 0; i
< f
->order
; i
++) {
1144 grid_edge
*e
= f
->edges
[i
];
1145 if (state
->lines
[e
- g
->edges
] == line_type
)
1151 /* Set all lines bordering a dot of type old_type to type new_type
1152 * Return value tells caller whether this function actually did anything */
1153 static int dot_setall(solver_state
*sstate
, int dot
,
1154 char old_type
, char new_type
)
1156 int retval
= FALSE
, r
;
1157 game_state
*state
= sstate
->state
;
1162 if (old_type
== new_type
)
1165 g
= state
->game_grid
;
1168 for (i
= 0; i
< d
->order
; i
++) {
1169 int line_index
= d
->edges
[i
] - g
->edges
;
1170 if (state
->lines
[line_index
] == old_type
) {
1171 r
= solver_set_line(sstate
, line_index
, new_type
);
1179 /* Set all lines bordering a face of type old_type to type new_type */
1180 static int face_setall(solver_state
*sstate
, int face
,
1181 char old_type
, char new_type
)
1183 int retval
= FALSE
, r
;
1184 game_state
*state
= sstate
->state
;
1189 if (old_type
== new_type
)
1192 g
= state
->game_grid
;
1193 f
= g
->faces
+ face
;
1195 for (i
= 0; i
< f
->order
; i
++) {
1196 int line_index
= f
->edges
[i
] - g
->edges
;
1197 if (state
->lines
[line_index
] == old_type
) {
1198 r
= solver_set_line(sstate
, line_index
, new_type
);
1206 /* ----------------------------------------------------------------------
1207 * Loop generation and clue removal
1210 /* We're going to store a list of current candidate faces for lighting.
1211 * Each face gets a 'score', which tells us how adding that face right
1212 * now would affect the length of the solution loop. We're trying to
1213 * maximise that quantity so will bias our random selection of faces to
1214 * light towards those with high scores */
1217 unsigned long random
;
1221 static int get_face_cmpfn(void *v1
, void *v2
)
1223 struct face
*f1
= v1
;
1224 struct face
*f2
= v2
;
1225 /* These grid_face pointers always point into the same list of
1226 * 'grid_face's, so it's valid to subtract them. */
1227 return f1
->f
- f2
->f
;
1230 static int face_sort_cmpfn(void *v1
, void *v2
)
1232 struct face
*f1
= v1
;
1233 struct face
*f2
= v2
;
1236 r
= f2
->score
- f1
->score
;
1241 if (f1
->random
< f2
->random
)
1243 else if (f1
->random
> f2
->random
)
1247 * It's _just_ possible that two faces might have been given
1248 * the same random value. In that situation, fall back to
1249 * comparing based on the positions within the grid's face-list.
1250 * This introduces a tiny directional bias, but not a significant one.
1252 return get_face_cmpfn(f1
, f2
);
1255 enum { FACE_LIT
, FACE_UNLIT
};
1257 /* face should be of type grid_face* here. */
1258 #define FACE_LIT_STATE(face) \
1259 ( (face) == NULL ? FACE_UNLIT : \
1260 board[(face) - g->faces] )
1262 /* 'board' is an array of these enums, indicating which faces are
1263 * currently lit. Returns whether it's legal to light up the
1265 static int can_light_face(grid
*g
, char* board
, int face_index
)
1268 grid_face
*test_face
= g
->faces
+ face_index
;
1269 grid_face
*starting_face
, *current_face
;
1271 int current_state
, s
;
1272 int found_lit_neighbour
= FALSE
;
1273 assert(board
[face_index
] == FACE_UNLIT
);
1275 /* Can only consider a face for lighting if it's adjacent to an
1276 * already lit face. */
1277 for (i
= 0; i
< test_face
->order
; i
++) {
1278 grid_edge
*e
= test_face
->edges
[i
];
1279 grid_face
*f
= (e
->face1
== test_face
) ? e
->face2
: e
->face1
;
1280 if (FACE_LIT_STATE(f
) == FACE_LIT
) {
1281 found_lit_neighbour
= TRUE
;
1285 if (!found_lit_neighbour
)
1288 /* Need to avoid creating a loop of lit faces around some unlit faces.
1289 * Also need to avoid meeting another lit face at a corner, with
1290 * unlit faces in between. Here's a simple test that (I believe) takes
1291 * care of both these conditions:
1293 * Take the circular path formed by this face's edges, and inflate it
1294 * slightly outwards. Imagine walking around this path and consider
1295 * the faces that you visit in sequence. This will include all faces
1296 * touching the given face, either along an edge or just at a corner.
1297 * Count the number of LIT/UNLIT transitions you encounter, as you walk
1298 * along the complete loop. This will obviously turn out to be an even
1300 * If 0, we're either in a completely unlit zone, or this face is a hole
1301 * in a completely lit zone. If the former, we would create a brand new
1302 * island by lighting this face. And the latter ought to be impossible -
1303 * it would mean there's already a lit loop, so something went wrong
1305 * If 4 or greater, there are too many separate lit regions touching this
1306 * face, and lighting it up would create a loop or a corner-violation.
1307 * The only allowed case is when the count is exactly 2. */
1309 /* i points to a dot around the test face.
1310 * j points to a face around the i^th dot.
1311 * The current face will always be:
1312 * test_face->dots[i]->faces[j]
1313 * We assume dots go clockwise around the test face,
1314 * and faces go clockwise around dots. */
1316 starting_face
= test_face
->dots
[0]->faces
[0];
1317 if (starting_face
== test_face
) {
1319 starting_face
= test_face
->dots
[0]->faces
[1];
1321 current_face
= starting_face
;
1323 current_state
= FACE_LIT_STATE(current_face
);
1326 /* Advance to next face.
1327 * Need to loop here because it might take several goes to
1331 if (j
== test_face
->dots
[i
]->order
)
1334 if (test_face
->dots
[i
]->faces
[j
] == test_face
) {
1335 /* Advance to next dot round test_face, then
1336 * find current_face around new dot
1337 * and advance to the next face clockwise */
1339 if (i
== test_face
->order
)
1341 for (j
= 0; j
< test_face
->dots
[i
]->order
; j
++) {
1342 if (test_face
->dots
[i
]->faces
[j
] == current_face
)
1345 /* Must actually find current_face around new dot,
1346 * or else something's wrong with the grid. */
1347 assert(j
!= test_face
->dots
[i
]->order
);
1348 /* Found, so advance to next face and try again */
1353 /* (i,j) are now advanced to next face */
1354 current_face
= test_face
->dots
[i
]->faces
[j
];
1355 s
= FACE_LIT_STATE(current_face
);
1356 if (s
!= current_state
) {
1359 if (transitions
> 2)
1360 return FALSE
; /* no point in continuing */
1362 } while (current_face
!= starting_face
);
1364 return (transitions
== 2) ? TRUE
: FALSE
;
1367 /* The 'score' of a face reflects its current desirability for selection
1368 * as the next face to light. We want to encourage moving into uncharted
1369 * areas so we give scores according to how many of the face's neighbours
1370 * are currently unlit. */
1371 static int face_score(grid
*g
, char *board
, grid_face
*face
)
1373 /* Simple formula: score = neighbours unlit - neighbours lit */
1374 int lit_count
= 0, unlit_count
= 0;
1378 for (i
= 0; i
< face
->order
; i
++) {
1380 f
= (e
->face1
== face
) ? e
->face2
: e
->face1
;
1381 if (FACE_LIT_STATE(f
) == FACE_LIT
)
1386 return unlit_count
- lit_count
;
1389 /* Generate a new complete set of clues for the given game_state. */
1390 static void add_full_clues(game_state
*state
, random_state
*rs
)
1392 signed char *clues
= state
->clues
;
1394 grid
*g
= state
->game_grid
;
1396 int num_faces
= g
->num_faces
;
1397 int first_time
= TRUE
;
1399 struct face
*face
, *tmpface
;
1400 struct face face_pos
;
1402 /* These will contain exactly the same information, sorted into different
1404 tree234
*lightable_faces_sorted
, *lightable_faces_gettable
;
1406 #define IS_LIGHTING_CANDIDATE(i) \
1407 (board[i] == FACE_UNLIT && \
1408 can_light_face(g, board, i))
1410 board
= snewn(num_faces
, char);
1413 memset(board
, FACE_UNLIT
, num_faces
);
1415 /* We need a way of favouring faces that will increase our loopiness.
1416 * We do this by maintaining a list of all candidate faces sorted by
1417 * their score and choose randomly from that with appropriate skew.
1418 * In order to avoid consistently biasing towards particular faces, we
1419 * need the sort order _within_ each group of scores to be completely
1420 * random. But it would be abusing the hospitality of the tree234 data
1421 * structure if our comparison function were nondeterministic :-). So with
1422 * each face we associate a random number that does not change during a
1423 * particular run of the generator, and use that as a secondary sort key.
1424 * Yes, this means we will be biased towards particular random faces in
1425 * any one run but that doesn't actually matter. */
1427 lightable_faces_sorted
= newtree234(face_sort_cmpfn
);
1428 lightable_faces_gettable
= newtree234(get_face_cmpfn
);
1429 #define ADD_FACE(f) \
1431 struct face *x = add234(lightable_faces_sorted, f); \
1433 x = add234(lightable_faces_gettable, f); \
1437 #define REMOVE_FACE(f) \
1439 struct face *x = del234(lightable_faces_sorted, f); \
1441 x = del234(lightable_faces_gettable, f); \
1445 /* Light faces one at a time until the board is interesting enough */
1450 /* lightable_faces_xxx are empty, so start the process by
1451 * lighting up the middle face. These tree234s should
1452 * remain empty, consistent with what would happen if
1453 * first_time were FALSE. */
1454 board
[g
->middle_face
- g
->faces
] = FACE_LIT
;
1455 face
= snew(struct face
);
1456 face
->f
= g
->middle_face
;
1457 /* No need to initialise any more of 'face' here, no other fields
1458 * are used in this case. */
1460 /* We have count234(lightable_faces_gettable) possibilities, and in
1461 * lightable_faces_sorted they are sorted with the most desirable
1463 c
= count234(lightable_faces_sorted
);
1466 assert(c
== count234(lightable_faces_gettable
));
1468 /* Check that the best face available is any good */
1469 face
= (struct face
*)index234(lightable_faces_sorted
, 0);
1473 * The situation for a general grid is slightly different from
1474 * a square grid. Decreasing the perimeter should be allowed
1475 * sometimes (think about creating a hexagon of lit triangles,
1476 * for example). For if it were _never_ done, then the user would
1477 * be able to illicitly deduce certain things. So we do it
1478 * sometimes but not always.
1480 if (face
->score
<= 0 && random_upto(rs
, 2) == 0) {
1484 assert(face
->f
); /* not the infinite face */
1485 assert(FACE_LIT_STATE(face
->f
) == FACE_UNLIT
);
1487 /* Update data structures */
1488 /* Light up the face and remove it from the lists */
1489 board
[face
->f
- g
->faces
] = FACE_LIT
;
1493 /* The face we've just lit up potentially affects the lightability
1494 * of any neighbouring faces (touching at a corner or edge). So the
1495 * search needs to be conducted around all faces touching the one
1496 * we've just lit. Iterate over its corners, then over each corner's
1498 for (i
= 0; i
< face
->f
->order
; i
++) {
1499 grid_dot
*d
= face
->f
->dots
[i
];
1500 for (j
= 0; j
< d
->order
; j
++) {
1501 grid_face
*f2
= d
->faces
[j
];
1507 tmpface
= find234(lightable_faces_gettable
, &face_pos
, NULL
);
1509 assert(tmpface
->f
== face_pos
.f
);
1510 assert(FACE_LIT_STATE(tmpface
->f
) == FACE_UNLIT
);
1511 REMOVE_FACE(tmpface
);
1513 tmpface
= snew(struct face
);
1514 tmpface
->f
= face_pos
.f
;
1515 tmpface
->random
= random_bits(rs
, 31);
1517 tmpface
->score
= face_score(g
, board
, tmpface
->f
);
1519 if (IS_LIGHTING_CANDIDATE(tmpface
->f
- g
->faces
)) {
1530 while ((face
= delpos234(lightable_faces_gettable
, 0)) != NULL
)
1532 freetree234(lightable_faces_gettable
);
1533 freetree234(lightable_faces_sorted
);
1535 /* Fill out all the clues by initialising to 0, then iterating over
1536 * all edges and incrementing each clue as we find edges that border
1537 * between LIT/UNLIT faces */
1538 memset(clues
, 0, num_faces
);
1539 for (i
= 0; i
< g
->num_edges
; i
++) {
1540 grid_edge
*e
= g
->edges
+ i
;
1541 grid_face
*f1
= e
->face1
;
1542 grid_face
*f2
= e
->face2
;
1543 if (FACE_LIT_STATE(f1
) != FACE_LIT_STATE(f2
)) {
1544 if (f1
) clues
[f1
- g
->faces
]++;
1545 if (f2
) clues
[f2
- g
->faces
]++;
1553 static int game_has_unique_soln(const game_state
*state
, int diff
)
1556 solver_state
*sstate_new
;
1557 solver_state
*sstate
= new_solver_state((game_state
*)state
, diff
);
1559 sstate_new
= solve_game_rec(sstate
, diff
);
1561 assert(sstate_new
->solver_status
!= SOLVER_MISTAKE
);
1562 ret
= (sstate_new
->solver_status
== SOLVER_SOLVED
);
1564 free_solver_state(sstate_new
);
1565 free_solver_state(sstate
);
1571 /* Remove clues one at a time at random. */
1572 static game_state
*remove_clues(game_state
*state
, random_state
*rs
,
1576 int num_faces
= state
->game_grid
->num_faces
;
1577 game_state
*ret
= dup_game(state
), *saved_ret
;
1580 /* We need to remove some clues. We'll do this by forming a list of all
1581 * available clues, shuffling it, then going along one at a
1582 * time clearing each clue in turn for which doing so doesn't render the
1583 * board unsolvable. */
1584 face_list
= snewn(num_faces
, int);
1585 for (n
= 0; n
< num_faces
; ++n
) {
1589 shuffle(face_list
, num_faces
, sizeof(int), rs
);
1591 for (n
= 0; n
< num_faces
; ++n
) {
1592 saved_ret
= dup_game(ret
);
1593 ret
->clues
[face_list
[n
]] = -1;
1595 if (game_has_unique_soln(ret
, diff
)) {
1596 free_game(saved_ret
);
1608 static char *new_game_desc(game_params
*params
, random_state
*rs
,
1609 char **aux
, int interactive
)
1611 /* solution and description both use run-length encoding in obvious ways */
1614 game_state
*state
= snew(game_state
);
1615 game_state
*state_new
;
1616 params_generate_grid(params
);
1617 state
->game_grid
= g
= params
->game_grid
;
1619 state
->clues
= snewn(g
->num_faces
, signed char);
1620 state
->lines
= snewn(g
->num_edges
, char);
1621 state
->line_errors
= snewn(g
->num_edges
, unsigned char);
1623 state
->grid_type
= params
->type
;
1627 memset(state
->lines
, LINE_UNKNOWN
, g
->num_edges
);
1628 memset(state
->line_errors
, 0, g
->num_edges
);
1630 state
->solved
= state
->cheated
= FALSE
;
1632 /* Get a new random solvable board with all its clues filled in. Yes, this
1633 * can loop for ever if the params are suitably unfavourable, but
1634 * preventing games smaller than 4x4 seems to stop this happening */
1636 add_full_clues(state
, rs
);
1637 } while (!game_has_unique_soln(state
, params
->diff
));
1639 state_new
= remove_clues(state
, rs
, params
->diff
);
1644 if (params
->diff
> 0 && game_has_unique_soln(state
, params
->diff
-1)) {
1646 fprintf(stderr
, "Rejecting board, it is too easy\n");
1648 goto newboard_please
;
1651 retval
= state_to_text(state
);
1655 assert(!validate_desc(params
, retval
));
1660 static game_state
*new_game(midend
*me
, game_params
*params
, char *desc
)
1663 game_state
*state
= snew(game_state
);
1664 int empties_to_make
= 0;
1666 const char *dp
= desc
;
1668 int num_faces
, num_edges
;
1670 params_generate_grid(params
);
1671 state
->game_grid
= g
= params
->game_grid
;
1673 num_faces
= g
->num_faces
;
1674 num_edges
= g
->num_edges
;
1676 state
->clues
= snewn(num_faces
, signed char);
1677 state
->lines
= snewn(num_edges
, char);
1678 state
->line_errors
= snewn(num_edges
, unsigned char);
1680 state
->solved
= state
->cheated
= FALSE
;
1682 state
->grid_type
= params
->type
;
1684 for (i
= 0; i
< num_faces
; i
++) {
1685 if (empties_to_make
) {
1687 state
->clues
[i
] = -1;
1693 if (n
>= 0 && n
< 10) {
1694 state
->clues
[i
] = n
;
1698 state
->clues
[i
] = -1;
1699 empties_to_make
= n
- 1;
1704 memset(state
->lines
, LINE_UNKNOWN
, num_edges
);
1705 memset(state
->line_errors
, 0, num_edges
);
1709 /* Calculates the line_errors data, and checks if the current state is a
1711 static int check_completion(game_state
*state
)
1713 grid
*g
= state
->game_grid
;
1715 int num_faces
= g
->num_faces
;
1717 int infinite_area
, finite_area
;
1718 int loops_found
= 0;
1719 int found_edge_not_in_loop
= FALSE
;
1721 memset(state
->line_errors
, 0, g
->num_edges
);
1723 /* LL implementation of SGT's idea:
1724 * A loop will partition the grid into an inside and an outside.
1725 * If there is more than one loop, the grid will be partitioned into
1726 * even more distinct regions. We can therefore track equivalence of
1727 * faces, by saying that two faces are equivalent when there is a non-YES
1728 * edge between them.
1729 * We could keep track of the number of connected components, by counting
1730 * the number of dsf-merges that aren't no-ops.
1731 * But we're only interested in 3 separate cases:
1732 * no loops, one loop, more than one loop.
1734 * No loops: all faces are equivalent to the infinite face.
1735 * One loop: only two equivalence classes - finite and infinite.
1736 * >= 2 loops: there are 2 distinct finite regions.
1738 * So we simply make two passes through all the edges.
1739 * In the first pass, we dsf-merge the two faces bordering each non-YES
1741 * In the second pass, we look for YES-edges bordering:
1742 * a) two non-equivalent faces.
1743 * b) two non-equivalent faces, and one of them is part of a different
1744 * finite area from the first finite area we've seen.
1746 * An occurrence of a) means there is at least one loop.
1747 * An occurrence of b) means there is more than one loop.
1748 * Edges satisfying a) are marked as errors.
1750 * While we're at it, we set a flag if we find a YES edge that is not
1752 * This information will help decide, if there's a single loop, whether it
1753 * is a candidate for being a solution (that is, all YES edges are part of
1756 * If there is a candidate loop, we then go through all clues and check
1757 * they are all satisfied. If so, we have found a solution and we can
1758 * unmark all line_errors.
1761 /* Infinite face is at the end - its index is num_faces.
1762 * This macro is just to make this obvious! */
1763 #define INF_FACE num_faces
1764 dsf
= snewn(num_faces
+ 1, int);
1765 dsf_init(dsf
, num_faces
+ 1);
1768 for (i
= 0; i
< g
->num_edges
; i
++) {
1769 grid_edge
*e
= g
->edges
+ i
;
1770 int f1
= e
->face1 ? e
->face1
- g
->faces
: INF_FACE
;
1771 int f2
= e
->face2 ? e
->face2
- g
->faces
: INF_FACE
;
1772 if (state
->lines
[i
] != LINE_YES
)
1773 dsf_merge(dsf
, f1
, f2
);
1777 infinite_area
= dsf_canonify(dsf
, INF_FACE
);
1779 for (i
= 0; i
< g
->num_edges
; i
++) {
1780 grid_edge
*e
= g
->edges
+ i
;
1781 int f1
= e
->face1 ? e
->face1
- g
->faces
: INF_FACE
;
1782 int can1
= dsf_canonify(dsf
, f1
);
1783 int f2
= e
->face2 ? e
->face2
- g
->faces
: INF_FACE
;
1784 int can2
= dsf_canonify(dsf
, f2
);
1785 if (state
->lines
[i
] != LINE_YES
) continue;
1788 /* Faces are equivalent, so this edge not part of a loop */
1789 found_edge_not_in_loop
= TRUE
;
1792 state
->line_errors
[i
] = TRUE
;
1793 if (loops_found
== 0) loops_found
= 1;
1795 /* Don't bother with further checks if we've already found 2 loops */
1796 if (loops_found
== 2) continue;
1798 if (finite_area
== -1) {
1799 /* Found our first finite area */
1800 if (can1
!= infinite_area
)
1806 /* Have we found a second area? */
1807 if (finite_area
!= -1) {
1808 if (can1
!= infinite_area
&& can1
!= finite_area
) {
1812 if (can2
!= infinite_area
&& can2
!= finite_area
) {
1819 printf("loops_found = %d\n", loops_found);
1820 printf("found_edge_not_in_loop = %s\n",
1821 found_edge_not_in_loop ? "TRUE" : "FALSE");
1824 sfree(dsf
); /* No longer need the dsf */
1826 /* Have we found a candidate loop? */
1827 if (loops_found
== 1 && !found_edge_not_in_loop
) {
1828 /* Yes, so check all clues are satisfied */
1829 int found_clue_violation
= FALSE
;
1830 for (i
= 0; i
< num_faces
; i
++) {
1831 int c
= state
->clues
[i
];
1833 if (face_order(state
, i
, LINE_YES
) != c
) {
1834 found_clue_violation
= TRUE
;
1840 if (!found_clue_violation
) {
1841 /* The loop is good */
1842 memset(state
->line_errors
, 0, g
->num_edges
);
1843 return TRUE
; /* No need to bother checking for dot violations */
1847 /* Check for dot violations */
1848 for (i
= 0; i
< g
->num_dots
; i
++) {
1849 int yes
= dot_order(state
, i
, LINE_YES
);
1850 int unknown
= dot_order(state
, i
, LINE_UNKNOWN
);
1851 if ((yes
== 1 && unknown
== 0) || (yes
>= 3)) {
1852 /* violation, so mark all YES edges as errors */
1853 grid_dot
*d
= g
->dots
+ i
;
1855 for (j
= 0; j
< d
->order
; j
++) {
1856 int e
= d
->edges
[j
] - g
->edges
;
1857 if (state
->lines
[e
] == LINE_YES
)
1858 state
->line_errors
[e
] = TRUE
;
1865 /* ----------------------------------------------------------------------
1868 * Our solver modes operate as follows. Each mode also uses the modes above it.
1871 * Just implement the rules of the game.
1874 * For each (adjacent) pair of lines through each dot we store a bit for
1875 * whether at least one of them is on and whether at most one is on. (If we
1876 * know both or neither is on that's already stored more directly.)
1879 * Use edsf data structure to make equivalence classes of lines that are
1880 * known identical to or opposite to one another.
1885 * For general grids, we consider "dlines" to be pairs of lines joined
1886 * at a dot. The lines must be adjacent around the dot, so we can think of
1887 * a dline as being a dot+face combination. Or, a dot+edge combination where
1888 * the second edge is taken to be the next clockwise edge from the dot.
1889 * Original loopy code didn't have this extra restriction of the lines being
1890 * adjacent. From my tests with square grids, this extra restriction seems to
1891 * take little, if anything, away from the quality of the puzzles.
1892 * A dline can be uniquely identified by an edge/dot combination, given that
1893 * a dline-pair always goes clockwise around its common dot. The edge/dot
1894 * combination can be represented by an edge/bool combination - if bool is
1895 * TRUE, use edge->dot1 else use edge->dot2. So the total number of dlines is
1896 * exactly twice the number of edges in the grid - although the dlines
1897 * spanning the infinite face are not all that useful to the solver.
1898 * Note that, by convention, a dline goes clockwise around its common dot,
1899 * which means the dline goes anti-clockwise around its common face.
1902 /* Helper functions for obtaining an index into an array of dlines, given
1903 * various information. We assume the grid layout conventions about how
1904 * the various lists are interleaved - see grid_make_consistent() for
1907 /* i points to the first edge of the dline pair, reading clockwise around
1909 static int dline_index_from_dot(grid
*g
, grid_dot
*d
, int i
)
1911 grid_edge
*e
= d
->edges
[i
];
1916 if (i2
== d
->order
) i2
= 0;
1919 ret
= 2 * (e
- g
->edges
) + ((e
->dot1
== d
) ?
1 : 0);
1921 printf("dline_index_from_dot: d=%d,i=%d, edges [%d,%d] - %d\n",
1922 (int)(d
- g
->dots
), i
, (int)(e
- g
->edges
),
1923 (int)(e2
- g
->edges
), ret
);
1927 /* i points to the second edge of the dline pair, reading clockwise around
1928 * the face. That is, the edges of the dline, starting at edge{i}, read
1929 * anti-clockwise around the face. By layout conventions, the common dot
1930 * of the dline will be f->dots[i] */
1931 static int dline_index_from_face(grid
*g
, grid_face
*f
, int i
)
1933 grid_edge
*e
= f
->edges
[i
];
1934 grid_dot
*d
= f
->dots
[i
];
1939 if (i2
< 0) i2
+= f
->order
;
1942 ret
= 2 * (e
- g
->edges
) + ((e
->dot1
== d
) ?
1 : 0);
1944 printf("dline_index_from_face: f=%d,i=%d, edges [%d,%d] - %d\n",
1945 (int)(f
- g
->faces
), i
, (int)(e
- g
->edges
),
1946 (int)(e2
- g
->edges
), ret
);
1950 static int is_atleastone(const char *dline_array
, int index
)
1952 return BIT_SET(dline_array
[index
], 0);
1954 static int set_atleastone(char *dline_array
, int index
)
1956 return SET_BIT(dline_array
[index
], 0);
1958 static int is_atmostone(const char *dline_array
, int index
)
1960 return BIT_SET(dline_array
[index
], 1);
1962 static int set_atmostone(char *dline_array
, int index
)
1964 return SET_BIT(dline_array
[index
], 1);
1967 static void array_setall(char *array
, char from
, char to
, int len
)
1969 char *p
= array
, *p_old
= p
;
1970 int len_remaining
= len
;
1972 while ((p
= memchr(p
, from
, len_remaining
))) {
1974 len_remaining
-= p
- p_old
;
1979 /* Helper, called when doing dline dot deductions, in the case where we
1980 * have 4 UNKNOWNs, and two of them (adjacent) have *exactly* one YES between
1981 * them (because of dline atmostone/atleastone).
1982 * On entry, edge points to the first of these two UNKNOWNs. This function
1983 * will find the opposite UNKNOWNS (if they are adjacent to one another)
1984 * and set their corresponding dline to atleastone. (Setting atmostone
1985 * already happens in earlier dline deductions) */
1986 static int dline_set_opp_atleastone(solver_state
*sstate
,
1987 grid_dot
*d
, int edge
)
1989 game_state
*state
= sstate
->state
;
1990 grid
*g
= state
->game_grid
;
1993 for (opp
= 0; opp
< N
; opp
++) {
1994 int opp_dline_index
;
1995 if (opp
== edge
|| opp
== edge
+1 || opp
== edge
-1)
1997 if (opp
== 0 && edge
== N
-1)
1999 if (opp
== N
-1 && edge
== 0)
2002 if (opp2
== N
) opp2
= 0;
2003 /* Check if opp, opp2 point to LINE_UNKNOWNs */
2004 if (state
->lines
[d
->edges
[opp
] - g
->edges
] != LINE_UNKNOWN
)
2006 if (state
->lines
[d
->edges
[opp2
] - g
->edges
] != LINE_UNKNOWN
)
2008 /* Found opposite UNKNOWNS and they're next to each other */
2009 opp_dline_index
= dline_index_from_dot(g
, d
, opp
);
2010 return set_atleastone(sstate
->normal
->dlines
, opp_dline_index
);
2016 /* Set pairs of lines around this face which are known to be identical, to
2017 * the given line_state */
2018 static int face_setall_identical(solver_state
*sstate
, int face_index
,
2019 enum line_state line_new
)
2021 /* can[dir] contains the canonical line associated with the line in
2022 * direction dir from the square in question. Similarly inv[dir] is
2023 * whether or not the line in question is inverse to its canonical
2026 game_state
*state
= sstate
->state
;
2027 grid
*g
= state
->game_grid
;
2028 grid_face
*f
= g
->faces
+ face_index
;
2031 int can1
, can2
, inv1
, inv2
;
2033 for (i
= 0; i
< N
; i
++) {
2034 int line1_index
= f
->edges
[i
] - g
->edges
;
2035 if (state
->lines
[line1_index
] != LINE_UNKNOWN
)
2037 for (j
= i
+ 1; j
< N
; j
++) {
2038 int line2_index
= f
->edges
[j
] - g
->edges
;
2039 if (state
->lines
[line2_index
] != LINE_UNKNOWN
)
2042 /* Found two UNKNOWNS */
2043 can1
= edsf_canonify(sstate
->hard
->linedsf
, line1_index
, &inv1
);
2044 can2
= edsf_canonify(sstate
->hard
->linedsf
, line2_index
, &inv2
);
2045 if (can1
== can2
&& inv1
== inv2
) {
2046 solver_set_line(sstate
, line1_index
, line_new
);
2047 solver_set_line(sstate
, line2_index
, line_new
);
2054 /* Given a dot or face, and a count of LINE_UNKNOWNs, find them and
2055 * return the edge indices into e. */
2056 static void find_unknowns(game_state
*state
,
2057 grid_edge
**edge_list
, /* Edge list to search (from a face or a dot) */
2058 int expected_count
, /* Number of UNKNOWNs (comes from solver's cache) */
2059 int *e
/* Returned edge indices */)
2062 grid
*g
= state
->game_grid
;
2063 while (c
< expected_count
) {
2064 int line_index
= *edge_list
- g
->edges
;
2065 if (state
->lines
[line_index
] == LINE_UNKNOWN
) {
2073 /* If we have a list of edges, and we know whether the number of YESs should
2074 * be odd or even, and there are only a few UNKNOWNs, we can do some simple
2075 * linedsf deductions. This can be used for both face and dot deductions.
2076 * Returns the difficulty level of the next solver that should be used,
2077 * or DIFF_MAX if no progress was made. */
2078 static int parity_deductions(solver_state
*sstate
,
2079 grid_edge
**edge_list
, /* Edge list (from a face or a dot) */
2080 int total_parity
, /* Expected number of YESs modulo 2 (either 0 or 1) */
2083 game_state
*state
= sstate
->state
;
2084 int diff
= DIFF_MAX
;
2085 int *linedsf
= sstate
->hard
->linedsf
;
2087 if (unknown_count
== 2) {
2088 /* Lines are known alike/opposite, depending on inv. */
2090 find_unknowns(state
, edge_list
, 2, e
);
2091 if (merge_lines(sstate
, e
[0], e
[1], total_parity
))
2092 diff
= min(diff
, DIFF_HARD
);
2093 } else if (unknown_count
== 3) {
2095 int can
[3]; /* canonical edges */
2096 int inv
[3]; /* whether can[x] is inverse to e[x] */
2097 find_unknowns(state
, edge_list
, 3, e
);
2098 can
[0] = edsf_canonify(linedsf
, e
[0], inv
);
2099 can
[1] = edsf_canonify(linedsf
, e
[1], inv
+1);
2100 can
[2] = edsf_canonify(linedsf
, e
[2], inv
+2);
2101 if (can
[0] == can
[1]) {
2102 if (solver_set_line(sstate
, e
[2], (total_parity
^inv
[0]^inv
[1]) ?
2103 LINE_YES
: LINE_NO
))
2104 diff
= min(diff
, DIFF_EASY
);
2106 if (can
[0] == can
[2]) {
2107 if (solver_set_line(sstate
, e
[1], (total_parity
^inv
[0]^inv
[2]) ?
2108 LINE_YES
: LINE_NO
))
2109 diff
= min(diff
, DIFF_EASY
);
2111 if (can
[1] == can
[2]) {
2112 if (solver_set_line(sstate
, e
[0], (total_parity
^inv
[1]^inv
[2]) ?
2113 LINE_YES
: LINE_NO
))
2114 diff
= min(diff
, DIFF_EASY
);
2116 } else if (unknown_count
== 4) {
2118 int can
[4]; /* canonical edges */
2119 int inv
[4]; /* whether can[x] is inverse to e[x] */
2120 find_unknowns(state
, edge_list
, 4, e
);
2121 can
[0] = edsf_canonify(linedsf
, e
[0], inv
);
2122 can
[1] = edsf_canonify(linedsf
, e
[1], inv
+1);
2123 can
[2] = edsf_canonify(linedsf
, e
[2], inv
+2);
2124 can
[3] = edsf_canonify(linedsf
, e
[3], inv
+3);
2125 if (can
[0] == can
[1]) {
2126 if (merge_lines(sstate
, e
[2], e
[3], total_parity
^inv
[0]^inv
[1]))
2127 diff
= min(diff
, DIFF_HARD
);
2128 } else if (can
[0] == can
[2]) {
2129 if (merge_lines(sstate
, e
[1], e
[3], total_parity
^inv
[0]^inv
[2]))
2130 diff
= min(diff
, DIFF_HARD
);
2131 } else if (can
[0] == can
[3]) {
2132 if (merge_lines(sstate
, e
[1], e
[2], total_parity
^inv
[0]^inv
[3]))
2133 diff
= min(diff
, DIFF_HARD
);
2134 } else if (can
[1] == can
[2]) {
2135 if (merge_lines(sstate
, e
[0], e
[3], total_parity
^inv
[1]^inv
[2]))
2136 diff
= min(diff
, DIFF_HARD
);
2137 } else if (can
[1] == can
[3]) {
2138 if (merge_lines(sstate
, e
[0], e
[2], total_parity
^inv
[1]^inv
[3]))
2139 diff
= min(diff
, DIFF_HARD
);
2140 } else if (can
[2] == can
[3]) {
2141 if (merge_lines(sstate
, e
[0], e
[1], total_parity
^inv
[2]^inv
[3]))
2142 diff
= min(diff
, DIFF_HARD
);
2150 * These are the main solver functions.
2152 * Their return values are diff values corresponding to the lowest mode solver
2153 * that would notice the work that they have done. For example if the normal
2154 * mode solver adds actual lines or crosses, it will return DIFF_EASY as the
2155 * easy mode solver might be able to make progress using that. It doesn't make
2156 * sense for one of them to return a diff value higher than that of the
2159 * Each function returns the lowest value it can, as early as possible, in
2160 * order to try and pass as much work as possible back to the lower level
2161 * solvers which progress more quickly.
2164 /* PROPOSED NEW DESIGN:
2165 * We have a work queue consisting of 'events' notifying us that something has
2166 * happened that a particular solver mode might be interested in. For example
2167 * the hard mode solver might do something that helps the normal mode solver at
2168 * dot [x,y] in which case it will enqueue an event recording this fact. Then
2169 * we pull events off the work queue, and hand each in turn to the solver that
2170 * is interested in them. If a solver reports that it failed we pass the same
2171 * event on to progressively more advanced solvers and the loop detector. Once
2172 * we've exhausted an event, or it has helped us progress, we drop it and
2173 * continue to the next one. The events are sorted first in order of solver
2174 * complexity (easy first) then order of insertion (oldest first).
2175 * Once we run out of events we loop over each permitted solver in turn
2176 * (easiest first) until either a deduction is made (and an event therefore
2177 * emerges) or no further deductions can be made (in which case we've failed).
2180 * * How do we 'loop over' a solver when both dots and squares are concerned.
2181 * Answer: first all squares then all dots.
2184 static int easy_mode_deductions(solver_state
*sstate
)
2186 int i
, current_yes
, current_no
;
2187 game_state
*state
= sstate
->state
;
2188 grid
*g
= state
->game_grid
;
2189 int diff
= DIFF_MAX
;
2191 /* Per-face deductions */
2192 for (i
= 0; i
< g
->num_faces
; i
++) {
2193 grid_face
*f
= g
->faces
+ i
;
2195 if (sstate
->face_solved
[i
])
2198 current_yes
= sstate
->face_yes_count
[i
];
2199 current_no
= sstate
->face_no_count
[i
];
2201 if (current_yes
+ current_no
== f
->order
) {
2202 sstate
->face_solved
[i
] = TRUE
;
2206 if (state
->clues
[i
] < 0)
2209 if (state
->clues
[i
] < current_yes
) {
2210 sstate
->solver_status
= SOLVER_MISTAKE
;
2213 if (state
->clues
[i
] == current_yes
) {
2214 if (face_setall(sstate
, i
, LINE_UNKNOWN
, LINE_NO
))
2215 diff
= min(diff
, DIFF_EASY
);
2216 sstate
->face_solved
[i
] = TRUE
;
2220 if (f
->order
- state
->clues
[i
] < current_no
) {
2221 sstate
->solver_status
= SOLVER_MISTAKE
;
2224 if (f
->order
- state
->clues
[i
] == current_no
) {
2225 if (face_setall(sstate
, i
, LINE_UNKNOWN
, LINE_YES
))
2226 diff
= min(diff
, DIFF_EASY
);
2227 sstate
->face_solved
[i
] = TRUE
;
2232 check_caches(sstate
);
2234 /* Per-dot deductions */
2235 for (i
= 0; i
< g
->num_dots
; i
++) {
2236 grid_dot
*d
= g
->dots
+ i
;
2237 int yes
, no
, unknown
;
2239 if (sstate
->dot_solved
[i
])
2242 yes
= sstate
->dot_yes_count
[i
];
2243 no
= sstate
->dot_no_count
[i
];
2244 unknown
= d
->order
- yes
- no
;
2248 sstate
->dot_solved
[i
] = TRUE
;
2249 } else if (unknown
== 1) {
2250 dot_setall(sstate
, i
, LINE_UNKNOWN
, LINE_NO
);
2251 diff
= min(diff
, DIFF_EASY
);
2252 sstate
->dot_solved
[i
] = TRUE
;
2254 } else if (yes
== 1) {
2256 sstate
->solver_status
= SOLVER_MISTAKE
;
2258 } else if (unknown
== 1) {
2259 dot_setall(sstate
, i
, LINE_UNKNOWN
, LINE_YES
);
2260 diff
= min(diff
, DIFF_EASY
);
2262 } else if (yes
== 2) {
2264 dot_setall(sstate
, i
, LINE_UNKNOWN
, LINE_NO
);
2265 diff
= min(diff
, DIFF_EASY
);
2267 sstate
->dot_solved
[i
] = TRUE
;
2269 sstate
->solver_status
= SOLVER_MISTAKE
;
2274 check_caches(sstate
);
2279 static int normal_mode_deductions(solver_state
*sstate
)
2281 game_state
*state
= sstate
->state
;
2282 grid
*g
= state
->game_grid
;
2283 char *dlines
= sstate
->normal
->dlines
;
2285 int diff
= DIFF_MAX
;
2287 /* ------ Face deductions ------ */
2289 /* Given a set of dline atmostone/atleastone constraints, need to figure
2290 * out if we can deduce any further info. For more general faces than
2291 * squares, this turns out to be a tricky problem.
2292 * The approach taken here is to define (per face) NxN matrices:
2293 * "maxs" and "mins".
2294 * The entries maxs(j,k) and mins(j,k) define the upper and lower limits
2295 * for the possible number of edges that are YES between positions j and k
2296 * going clockwise around the face. Can think of j and k as marking dots
2297 * around the face (recall the labelling scheme: edge0 joins dot0 to dot1,
2298 * edge1 joins dot1 to dot2 etc).
2299 * Trivially, mins(j,j) = maxs(j,j) = 0, and we don't even bother storing
2300 * these. mins(j,j+1) and maxs(j,j+1) are determined by whether edge{j}
2301 * is YES, NO or UNKNOWN. mins(j,j+2) and maxs(j,j+2) are related to
2302 * the dline atmostone/atleastone status for edges j and j+1.
2304 * Then we calculate the remaining entries recursively. We definitely
2306 * mins(j,k) >= { mins(j,u) + mins(u,k) } for any u between j and k.
2307 * This is because any valid placement of YESs between j and k must give
2308 * a valid placement between j and u, and also between u and k.
2309 * I believe it's sufficient to use just the two values of u:
2310 * j+1 and j+2. Seems to work well in practice - the bounds we compute
2311 * are rigorous, even if they might not be best-possible.
2313 * Once we have maxs and mins calculated, we can make inferences about
2314 * each dline{j,j+1} by looking at the possible complementary edge-counts
2315 * mins(j+2,j) and maxs(j+2,j) and comparing these with the face clue.
2316 * As well as dlines, we can make similar inferences about single edges.
2317 * For example, consider a pentagon with clue 3, and we know at most one
2318 * of (edge0, edge1) is YES, and at most one of (edge2, edge3) is YES.
2319 * We could then deduce edge4 is YES, because maxs(0,4) would be 2, so
2320 * that final edge would have to be YES to make the count up to 3.
2323 /* Much quicker to allocate arrays on the stack than the heap, so
2324 * define the largest possible face size, and base our array allocations
2325 * on that. We check this with an assertion, in case someone decides to
2326 * make a grid which has larger faces than this. Note, this algorithm
2327 * could get quite expensive if there are many large faces. */
2328 #define MAX_FACE_SIZE 8
2330 for (i
= 0; i
< g
->num_faces
; i
++) {
2331 int maxs
[MAX_FACE_SIZE
][MAX_FACE_SIZE
];
2332 int mins
[MAX_FACE_SIZE
][MAX_FACE_SIZE
];
2333 grid_face
*f
= g
->faces
+ i
;
2336 int clue
= state
->clues
[i
];
2337 assert(N
<= MAX_FACE_SIZE
);
2338 if (sstate
->face_solved
[i
])
2340 if (clue
< 0) continue;
2342 /* Calculate the (j,j+1) entries */
2343 for (j
= 0; j
< N
; j
++) {
2344 int edge_index
= f
->edges
[j
] - g
->edges
;
2346 enum line_state line1
= state
->lines
[edge_index
];
2347 enum line_state line2
;
2351 maxs
[j
][k
] = (line1
== LINE_NO
) ?
0 : 1;
2352 mins
[j
][k
] = (line1
== LINE_YES
) ?
1 : 0;
2353 /* Calculate the (j,j+2) entries */
2354 dline_index
= dline_index_from_face(g
, f
, k
);
2355 edge_index
= f
->edges
[k
] - g
->edges
;
2356 line2
= state
->lines
[edge_index
];
2362 if (line1
== LINE_NO
) tmp
--;
2363 if (line2
== LINE_NO
) tmp
--;
2364 if (tmp
== 2 && is_atmostone(dlines
, dline_index
))
2370 if (line1
== LINE_YES
) tmp
++;
2371 if (line2
== LINE_YES
) tmp
++;
2372 if (tmp
== 0 && is_atleastone(dlines
, dline_index
))
2377 /* Calculate the (j,j+m) entries for m between 3 and N-1 */
2378 for (m
= 3; m
< N
; m
++) {
2379 for (j
= 0; j
< N
; j
++) {
2387 maxs
[j
][k
] = maxs
[j
][u
] + maxs
[u
][k
];
2388 mins
[j
][k
] = mins
[j
][u
] + mins
[u
][k
];
2389 tmp
= maxs
[j
][v
] + maxs
[v
][k
];
2390 maxs
[j
][k
] = min(maxs
[j
][k
], tmp
);
2391 tmp
= mins
[j
][v
] + mins
[v
][k
];
2392 mins
[j
][k
] = max(mins
[j
][k
], tmp
);
2396 /* See if we can make any deductions */
2397 for (j
= 0; j
< N
; j
++) {
2399 grid_edge
*e
= f
->edges
[j
];
2400 int line_index
= e
- g
->edges
;
2403 if (state
->lines
[line_index
] != LINE_UNKNOWN
)
2408 /* minimum YESs in the complement of this edge */
2409 if (mins
[k
][j
] > clue
) {
2410 sstate
->solver_status
= SOLVER_MISTAKE
;
2413 if (mins
[k
][j
] == clue
) {
2414 /* setting this edge to YES would make at least
2415 * (clue+1) edges - contradiction */
2416 solver_set_line(sstate
, line_index
, LINE_NO
);
2417 diff
= min(diff
, DIFF_EASY
);
2419 if (maxs
[k
][j
] < clue
- 1) {
2420 sstate
->solver_status
= SOLVER_MISTAKE
;
2423 if (maxs
[k
][j
] == clue
- 1) {
2424 /* Only way to satisfy the clue is to set edge{j} as YES */
2425 solver_set_line(sstate
, line_index
, LINE_YES
);
2426 diff
= min(diff
, DIFF_EASY
);
2429 /* Now see if we can make dline deduction for edges{j,j+1} */
2431 if (state
->lines
[e
- g
->edges
] != LINE_UNKNOWN
)
2432 /* Only worth doing this for an UNKNOWN,UNKNOWN pair.
2433 * Dlines where one of the edges is known, are handled in the
2437 dline_index
= dline_index_from_face(g
, f
, k
);
2441 /* minimum YESs in the complement of this dline */
2442 if (mins
[k
][j
] > clue
- 2) {
2443 /* Adding 2 YESs would break the clue */
2444 if (set_atmostone(dlines
, dline_index
))
2445 diff
= min(diff
, DIFF_NORMAL
);
2447 /* maximum YESs in the complement of this dline */
2448 if (maxs
[k
][j
] < clue
) {
2449 /* Adding 2 NOs would mean not enough YESs */
2450 if (set_atleastone(dlines
, dline_index
))
2451 diff
= min(diff
, DIFF_NORMAL
);
2456 if (diff
< DIFF_NORMAL
)
2459 /* ------ Dot deductions ------ */
2461 for (i
= 0; i
< g
->num_dots
; i
++) {
2462 grid_dot
*d
= g
->dots
+ i
;
2464 int yes
, no
, unknown
;
2466 if (sstate
->dot_solved
[i
])
2468 yes
= sstate
->dot_yes_count
[i
];
2469 no
= sstate
->dot_no_count
[i
];
2470 unknown
= N
- yes
- no
;
2472 for (j
= 0; j
< N
; j
++) {
2475 int line1_index
, line2_index
;
2476 enum line_state line1
, line2
;
2479 dline_index
= dline_index_from_dot(g
, d
, j
);
2480 line1_index
= d
->edges
[j
] - g
->edges
;
2481 line2_index
= d
->edges
[k
] - g
->edges
;
2482 line1
= state
->lines
[line1_index
];
2483 line2
= state
->lines
[line2_index
];
2485 /* Infer dline state from line state */
2486 if (line1
== LINE_NO
|| line2
== LINE_NO
) {
2487 if (set_atmostone(dlines
, dline_index
))
2488 diff
= min(diff
, DIFF_NORMAL
);
2490 if (line1
== LINE_YES
|| line2
== LINE_YES
) {
2491 if (set_atleastone(dlines
, dline_index
))
2492 diff
= min(diff
, DIFF_NORMAL
);
2494 /* Infer line state from dline state */
2495 if (is_atmostone(dlines
, dline_index
)) {
2496 if (line1
== LINE_YES
&& line2
== LINE_UNKNOWN
) {
2497 solver_set_line(sstate
, line2_index
, LINE_NO
);
2498 diff
= min(diff
, DIFF_EASY
);
2500 if (line2
== LINE_YES
&& line1
== LINE_UNKNOWN
) {
2501 solver_set_line(sstate
, line1_index
, LINE_NO
);
2502 diff
= min(diff
, DIFF_EASY
);
2505 if (is_atleastone(dlines
, dline_index
)) {
2506 if (line1
== LINE_NO
&& line2
== LINE_UNKNOWN
) {
2507 solver_set_line(sstate
, line2_index
, LINE_YES
);
2508 diff
= min(diff
, DIFF_EASY
);
2510 if (line2
== LINE_NO
&& line1
== LINE_UNKNOWN
) {
2511 solver_set_line(sstate
, line1_index
, LINE_YES
);
2512 diff
= min(diff
, DIFF_EASY
);
2515 /* Deductions that depend on the numbers of lines.
2516 * Only bother if both lines are UNKNOWN, otherwise the
2517 * easy-mode solver (or deductions above) would have taken
2519 if (line1
!= LINE_UNKNOWN
|| line2
!= LINE_UNKNOWN
)
2522 if (yes
== 0 && unknown
== 2) {
2523 /* Both these unknowns must be identical. If we know
2524 * atmostone or atleastone, we can make progress. */
2525 if (is_atmostone(dlines
, dline_index
)) {
2526 solver_set_line(sstate
, line1_index
, LINE_NO
);
2527 solver_set_line(sstate
, line2_index
, LINE_NO
);
2528 diff
= min(diff
, DIFF_EASY
);
2530 if (is_atleastone(dlines
, dline_index
)) {
2531 solver_set_line(sstate
, line1_index
, LINE_YES
);
2532 solver_set_line(sstate
, line2_index
, LINE_YES
);
2533 diff
= min(diff
, DIFF_EASY
);
2537 if (set_atmostone(dlines
, dline_index
))
2538 diff
= min(diff
, DIFF_NORMAL
);
2540 if (set_atleastone(dlines
, dline_index
))
2541 diff
= min(diff
, DIFF_NORMAL
);
2545 /* If we have atleastone set for this dline, infer
2546 * atmostone for each "opposite" dline (that is, each
2547 * dline without edges in common with this one).
2548 * Again, this test is only worth doing if both these
2549 * lines are UNKNOWN. For if one of these lines were YES,
2550 * the (yes == 1) test above would kick in instead. */
2551 if (is_atleastone(dlines
, dline_index
)) {
2553 for (opp
= 0; opp
< N
; opp
++) {
2554 int opp_dline_index
;
2555 if (opp
== j
|| opp
== j
+1 || opp
== j
-1)
2557 if (j
== 0 && opp
== N
-1)
2559 if (j
== N
-1 && opp
== 0)
2561 opp_dline_index
= dline_index_from_dot(g
, d
, opp
);
2562 if (set_atmostone(dlines
, opp_dline_index
))
2563 diff
= min(diff
, DIFF_NORMAL
);
2566 if (yes
== 0 && is_atmostone(dlines
, dline_index
)) {
2567 /* This dline has *exactly* one YES and there are no
2568 * other YESs. This allows more deductions. */
2570 /* Third unknown must be YES */
2571 for (opp
= 0; opp
< N
; opp
++) {
2573 if (opp
== j
|| opp
== k
)
2575 opp_index
= d
->edges
[opp
] - g
->edges
;
2576 if (state
->lines
[opp_index
] == LINE_UNKNOWN
) {
2577 solver_set_line(sstate
, opp_index
, LINE_YES
);
2578 diff
= min(diff
, DIFF_EASY
);
2581 } else if (unknown
== 4) {
2582 /* Exactly one of opposite UNKNOWNS is YES. We've
2583 * already set atmostone, so set atleastone as well.
2585 if (dline_set_opp_atleastone(sstate
, d
, j
))
2586 diff
= min(diff
, DIFF_NORMAL
);
2595 static int hard_mode_deductions(solver_state
*sstate
)
2597 game_state
*state
= sstate
->state
;
2598 grid
*g
= state
->game_grid
;
2599 char *dlines
= sstate
->normal
->dlines
;
2601 int diff
= DIFF_MAX
;
2604 /* ------ Face deductions ------ */
2606 /* A fully-general linedsf deduction seems overly complicated
2607 * (I suspect the problem is NP-complete, though in practice it might just
2608 * be doable because faces are limited in size).
2609 * For simplicity, we only consider *pairs* of LINE_UNKNOWNS that are
2610 * known to be identical. If setting them both to YES (or NO) would break
2611 * the clue, set them to NO (or YES). */
2613 for (i
= 0; i
< g
->num_faces
; i
++) {
2614 int N
, yes
, no
, unknown
;
2617 if (sstate
->face_solved
[i
])
2619 clue
= state
->clues
[i
];
2623 N
= g
->faces
[i
].order
;
2624 yes
= sstate
->face_yes_count
[i
];
2625 if (yes
+ 1 == clue
) {
2626 if (face_setall_identical(sstate
, i
, LINE_NO
))
2627 diff
= min(diff
, DIFF_EASY
);
2629 no
= sstate
->face_no_count
[i
];
2630 if (no
+ 1 == N
- clue
) {
2631 if (face_setall_identical(sstate
, i
, LINE_YES
))
2632 diff
= min(diff
, DIFF_EASY
);
2635 /* Reload YES count, it might have changed */
2636 yes
= sstate
->face_yes_count
[i
];
2637 unknown
= N
- no
- yes
;
2639 /* Deductions with small number of LINE_UNKNOWNs, based on overall
2640 * parity of lines. */
2641 diff_tmp
= parity_deductions(sstate
, g
->faces
[i
].edges
,
2642 (clue
- yes
) % 2, unknown
);
2643 diff
= min(diff
, diff_tmp
);
2646 /* ------ Dot deductions ------ */
2647 for (i
= 0; i
< g
->num_dots
; i
++) {
2648 grid_dot
*d
= g
->dots
+ i
;
2651 int yes
, no
, unknown
;
2652 /* Go through dlines, and do any dline<->linedsf deductions wherever
2653 * we find two UNKNOWNS. */
2654 for (j
= 0; j
< N
; j
++) {
2655 int dline_index
= dline_index_from_dot(g
, d
, j
);
2658 int can1
, can2
, inv1
, inv2
;
2660 line1_index
= d
->edges
[j
] - g
->edges
;
2661 if (state
->lines
[line1_index
] != LINE_UNKNOWN
)
2664 if (j2
== N
) j2
= 0;
2665 line2_index
= d
->edges
[j2
] - g
->edges
;
2666 if (state
->lines
[line2_index
] != LINE_UNKNOWN
)
2668 /* Infer dline flags from linedsf */
2669 can1
= edsf_canonify(sstate
->hard
->linedsf
, line1_index
, &inv1
);
2670 can2
= edsf_canonify(sstate
->hard
->linedsf
, line2_index
, &inv2
);
2671 if (can1
== can2
&& inv1
!= inv2
) {
2672 /* These are opposites, so set dline atmostone/atleastone */
2673 if (set_atmostone(dlines
, dline_index
))
2674 diff
= min(diff
, DIFF_NORMAL
);
2675 if (set_atleastone(dlines
, dline_index
))
2676 diff
= min(diff
, DIFF_NORMAL
);
2679 /* Infer linedsf from dline flags */
2680 if (is_atmostone(dlines
, dline_index
)
2681 && is_atleastone(dlines
, dline_index
)) {
2682 if (merge_lines(sstate
, line1_index
, line2_index
, 1))
2683 diff
= min(diff
, DIFF_HARD
);
2687 /* Deductions with small number of LINE_UNKNOWNs, based on overall
2688 * parity of lines. */
2689 yes
= sstate
->dot_yes_count
[i
];
2690 no
= sstate
->dot_no_count
[i
];
2691 unknown
= N
- yes
- no
;
2692 diff_tmp
= parity_deductions(sstate
, d
->edges
,
2694 diff
= min(diff
, diff_tmp
);
2697 /* ------ Edge dsf deductions ------ */
2699 /* If the state of a line is known, deduce the state of its canonical line
2700 * too, and vice versa. */
2701 for (i
= 0; i
< g
->num_edges
; i
++) {
2704 can
= edsf_canonify(sstate
->hard
->linedsf
, i
, &inv
);
2707 s
= sstate
->state
->lines
[can
];
2708 if (s
!= LINE_UNKNOWN
) {
2709 if (solver_set_line(sstate
, i
, inv ?
OPP(s
) : s
))
2710 diff
= min(diff
, DIFF_EASY
);
2712 s
= sstate
->state
->lines
[i
];
2713 if (s
!= LINE_UNKNOWN
) {
2714 if (solver_set_line(sstate
, can
, inv ?
OPP(s
) : s
))
2715 diff
= min(diff
, DIFF_EASY
);
2723 static int loop_deductions(solver_state
*sstate
)
2725 int edgecount
= 0, clues
= 0, satclues
= 0, sm1clues
= 0;
2726 game_state
*state
= sstate
->state
;
2727 grid
*g
= state
->game_grid
;
2728 int shortest_chainlen
= g
->num_dots
;
2729 int loop_found
= FALSE
;
2731 int progress
= FALSE
;
2735 * Go through the grid and update for all the new edges.
2736 * Since merge_dots() is idempotent, the simplest way to
2737 * do this is just to update for _all_ the edges.
2738 * Also, while we're here, we count the edges.
2740 for (i
= 0; i
< g
->num_edges
; i
++) {
2741 if (state
->lines
[i
] == LINE_YES
) {
2742 loop_found
|= merge_dots(sstate
, i
);
2748 * Count the clues, count the satisfied clues, and count the
2749 * satisfied-minus-one clues.
2751 for (i
= 0; i
< g
->num_faces
; i
++) {
2752 int c
= state
->clues
[i
];
2754 int o
= sstate
->face_yes_count
[i
];
2763 for (i
= 0; i
< g
->num_dots
; ++i
) {
2765 sstate
->looplen
[dsf_canonify(sstate
->dotdsf
, i
)];
2766 if (dots_connected
> 1)
2767 shortest_chainlen
= min(shortest_chainlen
, dots_connected
);
2770 assert(sstate
->solver_status
== SOLVER_INCOMPLETE
);
2772 if (satclues
== clues
&& shortest_chainlen
== edgecount
) {
2773 sstate
->solver_status
= SOLVER_SOLVED
;
2774 /* This discovery clearly counts as progress, even if we haven't
2775 * just added any lines or anything */
2777 goto finished_loop_deductionsing
;
2781 * Now go through looking for LINE_UNKNOWN edges which
2782 * connect two dots that are already in the same
2783 * equivalence class. If we find one, test to see if the
2784 * loop it would create is a solution.
2786 for (i
= 0; i
< g
->num_edges
; i
++) {
2787 grid_edge
*e
= g
->edges
+ i
;
2788 int d1
= e
->dot1
- g
->dots
;
2789 int d2
= e
->dot2
- g
->dots
;
2791 if (state
->lines
[i
] != LINE_UNKNOWN
)
2794 eqclass
= dsf_canonify(sstate
->dotdsf
, d1
);
2795 if (eqclass
!= dsf_canonify(sstate
->dotdsf
, d2
))
2798 val
= LINE_NO
; /* loop is bad until proven otherwise */
2801 * This edge would form a loop. Next
2802 * question: how long would the loop be?
2803 * Would it equal the total number of edges
2804 * (plus the one we'd be adding if we added
2807 if (sstate
->looplen
[eqclass
] == edgecount
+ 1) {
2811 * This edge would form a loop which
2812 * took in all the edges in the entire
2813 * grid. So now we need to work out
2814 * whether it would be a valid solution
2815 * to the puzzle, which means we have to
2816 * check if it satisfies all the clues.
2817 * This means that every clue must be
2818 * either satisfied or satisfied-minus-
2819 * 1, and also that the number of
2820 * satisfied-minus-1 clues must be at
2821 * most two and they must lie on either
2822 * side of this edge.
2826 int f
= e
->face1
- g
->faces
;
2827 int c
= state
->clues
[f
];
2828 if (c
>= 0 && sstate
->face_yes_count
[f
] == c
- 1)
2832 int f
= e
->face2
- g
->faces
;
2833 int c
= state
->clues
[f
];
2834 if (c
>= 0 && sstate
->face_yes_count
[f
] == c
- 1)
2837 if (sm1clues
== sm1_nearby
&&
2838 sm1clues
+ satclues
== clues
) {
2839 val
= LINE_YES
; /* loop is good! */
2844 * Right. Now we know that adding this edge
2845 * would form a loop, and we know whether
2846 * that loop would be a viable solution or
2849 * If adding this edge produces a solution,
2850 * then we know we've found _a_ solution but
2851 * we don't know that it's _the_ solution -
2852 * if it were provably the solution then
2853 * we'd have deduced this edge some time ago
2854 * without the need to do loop detection. So
2855 * in this state we return SOLVER_AMBIGUOUS,
2856 * which has the effect that hitting Solve
2857 * on a user-provided puzzle will fill in a
2858 * solution but using the solver to
2859 * construct new puzzles won't consider this
2860 * a reasonable deduction for the user to
2863 progress
= solver_set_line(sstate
, i
, val
);
2864 assert(progress
== TRUE
);
2865 if (val
== LINE_YES
) {
2866 sstate
->solver_status
= SOLVER_AMBIGUOUS
;
2867 goto finished_loop_deductionsing
;
2871 finished_loop_deductionsing
:
2872 return progress ? DIFF_EASY
: DIFF_MAX
;
2875 /* This will return a dynamically allocated solver_state containing the (more)
2877 static solver_state
*solve_game_rec(const solver_state
*sstate_start
,
2880 solver_state
*sstate
, *sstate_saved
;
2881 int solver_progress
;
2884 /* Indicates which solver we should call next. This is a sensible starting
2886 int current_solver
= DIFF_EASY
, next_solver
;
2887 sstate
= dup_solver_state(sstate_start
);
2889 /* Cache the values of some variables for readability */
2890 state
= sstate
->state
;
2892 sstate_saved
= NULL
;
2894 solver_progress
= FALSE
;
2896 check_caches(sstate
);
2899 if (sstate
->solver_status
== SOLVER_MISTAKE
)
2902 next_solver
= solver_fns
[current_solver
](sstate
);
2904 if (next_solver
== DIFF_MAX
) {
2905 if (current_solver
< diff
&& current_solver
+ 1 < DIFF_MAX
) {
2906 /* Try next beefier solver */
2907 next_solver
= current_solver
+ 1;
2909 next_solver
= loop_deductions(sstate
);
2913 if (sstate
->solver_status
== SOLVER_SOLVED
||
2914 sstate
->solver_status
== SOLVER_AMBIGUOUS
) {
2915 /* fprintf(stderr, "Solver completed\n"); */
2919 /* Once we've looped over all permitted solvers then the loop
2920 * deductions without making any progress, we'll exit this while loop */
2921 current_solver
= next_solver
;
2922 } while (current_solver
< DIFF_MAX
);
2924 if (sstate
->solver_status
== SOLVER_SOLVED
||
2925 sstate
->solver_status
== SOLVER_AMBIGUOUS
) {
2926 /* s/LINE_UNKNOWN/LINE_NO/g */
2927 array_setall(sstate
->state
->lines
, LINE_UNKNOWN
, LINE_NO
,
2928 sstate
->state
->game_grid
->num_edges
);
2935 static char *solve_game(game_state
*state
, game_state
*currstate
,
2936 char *aux
, char **error
)
2939 solver_state
*sstate
, *new_sstate
;
2941 sstate
= new_solver_state(state
, DIFF_MAX
);
2942 new_sstate
= solve_game_rec(sstate
, DIFF_MAX
);
2944 if (new_sstate
->solver_status
== SOLVER_SOLVED
) {
2945 soln
= encode_solve_move(new_sstate
->state
);
2946 } else if (new_sstate
->solver_status
== SOLVER_AMBIGUOUS
) {
2947 soln
= encode_solve_move(new_sstate
->state
);
2948 /**error = "Solver found ambiguous solutions"; */
2950 soln
= encode_solve_move(new_sstate
->state
);
2951 /**error = "Solver failed"; */
2954 free_solver_state(new_sstate
);
2955 free_solver_state(sstate
);
2960 /* ----------------------------------------------------------------------
2961 * Drawing and mouse-handling
2964 static char *interpret_move(game_state
*state
, game_ui
*ui
, game_drawstate
*ds
,
2965 int x
, int y
, int button
)
2967 grid
*g
= state
->game_grid
;
2971 char button_char
= ' ';
2972 enum line_state old_state
;
2974 button
&= ~MOD_MASK
;
2976 /* Convert mouse-click (x,y) to grid coordinates */
2977 x
-= BORDER(ds
->tilesize
);
2978 y
-= BORDER(ds
->tilesize
);
2979 x
= x
* g
->tilesize
/ ds
->tilesize
;
2980 y
= y
* g
->tilesize
/ ds
->tilesize
;
2984 e
= grid_nearest_edge(g
, x
, y
);
2990 /* I think it's only possible to play this game with mouse clicks, sorry */
2991 /* Maybe will add mouse drag support some time */
2992 old_state
= state
->lines
[i
];
2996 switch (old_state
) {
3010 switch (old_state
) {
3025 sprintf(buf
, "%d%c", i
, (int)button_char
);
3031 static game_state
*execute_move(game_state
*state
, char *move
)
3034 game_state
*newstate
= dup_game(state
);
3036 if (move
[0] == 'S') {
3038 newstate
->cheated
= TRUE
;
3043 move
+= strspn(move
, "1234567890");
3044 switch (*(move
++)) {
3046 newstate
->lines
[i
] = LINE_YES
;
3049 newstate
->lines
[i
] = LINE_NO
;
3052 newstate
->lines
[i
] = LINE_UNKNOWN
;
3060 * Check for completion.
3062 if (check_completion(newstate
))
3063 newstate
->solved
= TRUE
;
3068 free_game(newstate
);
3072 /* ----------------------------------------------------------------------
3076 /* Convert from grid coordinates to screen coordinates */
3077 static void grid_to_screen(const game_drawstate
*ds
, const grid
*g
,
3078 int grid_x
, int grid_y
, int *x
, int *y
)
3080 *x
= grid_x
- g
->lowest_x
;
3081 *y
= grid_y
- g
->lowest_y
;
3082 *x
= *x
* ds
->tilesize
/ g
->tilesize
;
3083 *y
= *y
* ds
->tilesize
/ g
->tilesize
;
3084 *x
+= BORDER(ds
->tilesize
);
3085 *y
+= BORDER(ds
->tilesize
);
3088 /* Returns (into x,y) position of centre of face for rendering the text clue.
3090 static void face_text_pos(const game_drawstate
*ds
, const grid
*g
,
3091 const grid_face
*f
, int *x
, int *y
)
3095 /* Simplest solution is the centroid. Might not work in some cases. */
3097 /* Another algorithm to look into:
3098 * Find the midpoints of the sides, find the bounding-box,
3099 * then take the centre of that. */
3101 /* Best solution probably involves incentres (inscribed circles) */
3103 int sx
= 0, sy
= 0; /* sums */
3104 for (i
= 0; i
< f
->order
; i
++) {
3105 grid_dot
*d
= f
->dots
[i
];
3112 /* convert to screen coordinates */
3113 grid_to_screen(ds
, g
, sx
, sy
, x
, y
);
3116 static void game_redraw(drawing
*dr
, game_drawstate
*ds
, game_state
*oldstate
,
3117 game_state
*state
, int dir
, game_ui
*ui
,
3118 float animtime
, float flashtime
)
3120 grid
*g
= state
->game_grid
;
3121 int border
= BORDER(ds
->tilesize
);
3124 int line_colour
, flash_changed
;
3130 * The initial contents of the window are not guaranteed and
3131 * can vary with front ends. To be on the safe side, all games
3132 * should start by drawing a big background-colour rectangle
3133 * covering the whole window.
3135 int grid_width
= g
->highest_x
- g
->lowest_x
;
3136 int grid_height
= g
->highest_y
- g
->lowest_y
;
3137 int w
= grid_width
* ds
->tilesize
/ g
->tilesize
;
3138 int h
= grid_height
* ds
->tilesize
/ g
->tilesize
;
3139 draw_rect(dr
, 0, 0, w
+ 2 * border
+ 1, h
+ 2 * border
+ 1,
3143 for (i
= 0; i
< g
->num_faces
; i
++) {
3147 c
[0] = CLUE2CHAR(state
->clues
[i
]);
3150 face_text_pos(ds
, g
, f
, &x
, &y
);
3151 draw_text(dr
, x
, y
, FONT_VARIABLE
, ds
->tilesize
/2,
3152 ALIGN_VCENTRE
| ALIGN_HCENTRE
, COL_FOREGROUND
, c
);
3154 draw_update(dr
, 0, 0, w
+ 2 * border
, h
+ 2 * border
);
3157 if (flashtime
> 0 &&
3158 (flashtime
<= FLASH_TIME
/3 ||
3159 flashtime
>= FLASH_TIME
*2/3)) {
3160 flash_changed
= !ds
->flashing
;
3161 ds
->flashing
= TRUE
;
3163 flash_changed
= ds
->flashing
;
3164 ds
->flashing
= FALSE
;
3167 /* Some platforms may perform anti-aliasing, which may prevent clean
3168 * repainting of lines when the colour is changed.
3169 * If a line needs to be over-drawn in a different colour, erase a
3170 * bounding-box around the line, then flag all nearby objects for redraw.
3173 const char redraw_flag
= (char)(1<<7);
3174 for (i
= 0; i
< g
->num_edges
; i
++) {
3175 char prev_ds
= (ds
->lines
[i
] & ~redraw_flag
);
3176 char new_ds
= state
->lines
[i
];
3177 if (state
->line_errors
[i
])
3178 new_ds
= DS_LINE_ERROR
;
3180 /* If we're changing state, AND
3181 * the previous state was a coloured line */
3182 if ((prev_ds
!= new_ds
) && (prev_ds
!= LINE_NO
)) {
3183 grid_edge
*e
= g
->edges
+ i
;
3184 int x1
= e
->dot1
->x
;
3185 int y1
= e
->dot1
->y
;
3186 int x2
= e
->dot2
->x
;
3187 int y2
= e
->dot2
->y
;
3188 int xmin
, xmax
, ymin
, ymax
;
3190 grid_to_screen(ds
, g
, x1
, y1
, &x1
, &y1
);
3191 grid_to_screen(ds
, g
, x2
, y2
, &x2
, &y2
);
3192 /* Allow extra margin for dots, and thickness of lines */
3193 xmin
= min(x1
, x2
) - 2;
3194 xmax
= max(x1
, x2
) + 2;
3195 ymin
= min(y1
, y2
) - 2;
3196 ymax
= max(y1
, y2
) + 2;
3197 /* For testing, I find it helpful to change COL_BACKGROUND
3198 * to COL_SATISFIED here. */
3199 draw_rect(dr
, xmin
, ymin
, xmax
- xmin
+ 1, ymax
- ymin
+ 1,
3201 draw_update(dr
, xmin
, ymin
, xmax
- xmin
+ 1, ymax
- ymin
+ 1);
3203 /* Mark nearby lines for redraw */
3204 for (j
= 0; j
< e
->dot1
->order
; j
++)
3205 ds
->lines
[e
->dot1
->edges
[j
] - g
->edges
] |= redraw_flag
;
3206 for (j
= 0; j
< e
->dot2
->order
; j
++)
3207 ds
->lines
[e
->dot2
->edges
[j
] - g
->edges
] |= redraw_flag
;
3208 /* Mark nearby clues for redraw. Use a value that is
3209 * neither TRUE nor FALSE for this. */
3211 ds
->clue_error
[e
->face1
- g
->faces
] = 2;
3213 ds
->clue_error
[e
->face2
- g
->faces
] = 2;
3218 /* Redraw clue colours if necessary */
3219 for (i
= 0; i
< g
->num_faces
; i
++) {
3220 grid_face
*f
= g
->faces
+ i
;
3221 int sides
= f
->order
;
3223 n
= state
->clues
[i
];
3227 c
[0] = CLUE2CHAR(n
);
3230 clue_mistake
= (face_order(state
, i
, LINE_YES
) > n
||
3231 face_order(state
, i
, LINE_NO
) > (sides
-n
));
3233 clue_satisfied
= (face_order(state
, i
, LINE_YES
) == n
&&
3234 face_order(state
, i
, LINE_NO
) == (sides
-n
));
3236 if (clue_mistake
!= ds
->clue_error
[i
]
3237 || clue_satisfied
!= ds
->clue_satisfied
[i
]) {
3239 face_text_pos(ds
, g
, f
, &x
, &y
);
3240 /* There seems to be a certain amount of trial-and-error
3241 * involved in working out the correct bounding-box for
3243 draw_rect(dr
, x
- ds
->tilesize
/4 - 1, y
- ds
->tilesize
/4 - 3,
3244 ds
->tilesize
/2 + 2, ds
->tilesize
/2 + 5,
3247 FONT_VARIABLE
, ds
->tilesize
/2,
3248 ALIGN_VCENTRE
| ALIGN_HCENTRE
,
3249 clue_mistake ? COL_MISTAKE
:
3250 clue_satisfied ? COL_SATISFIED
: COL_FOREGROUND
, c
);
3251 draw_update(dr
, x
- ds
->tilesize
/4 - 1, y
- ds
->tilesize
/4 - 3,
3252 ds
->tilesize
/2 + 2, ds
->tilesize
/2 + 5);
3254 ds
->clue_error
[i
] = clue_mistake
;
3255 ds
->clue_satisfied
[i
] = clue_satisfied
;
3257 /* Sometimes, the bounding-box encroaches into the surrounding
3258 * lines (particularly if the window is resized fairly small).
3259 * So redraw them. */
3260 for (j
= 0; j
< f
->order
; j
++)
3261 ds
->lines
[f
->edges
[j
] - g
->edges
] = -1;
3266 for (i
= 0; i
< g
->num_edges
; i
++) {
3267 grid_edge
*e
= g
->edges
+ i
;
3269 int xmin
, ymin
, xmax
, ymax
;
3270 char new_ds
, need_draw
;
3271 new_ds
= state
->lines
[i
];
3272 if (state
->line_errors
[i
])
3273 new_ds
= DS_LINE_ERROR
;
3274 need_draw
= (new_ds
!= ds
->lines
[i
]) ? TRUE
: FALSE
;
3275 if (flash_changed
&& (state
->lines
[i
] == LINE_YES
))
3278 need_draw
= TRUE
; /* draw everything at the start */
3279 ds
->lines
[i
] = new_ds
;
3282 if (state
->line_errors
[i
])
3283 line_colour
= COL_MISTAKE
;
3284 else if (state
->lines
[i
] == LINE_UNKNOWN
)
3285 line_colour
= COL_LINEUNKNOWN
;
3286 else if (state
->lines
[i
] == LINE_NO
)
3287 line_colour
= COL_BACKGROUND
;
3288 else if (ds
->flashing
)
3289 line_colour
= COL_HIGHLIGHT
;
3291 line_colour
= COL_FOREGROUND
;
3293 /* Convert from grid to screen coordinates */
3294 grid_to_screen(ds
, g
, e
->dot1
->x
, e
->dot1
->y
, &x1
, &y1
);
3295 grid_to_screen(ds
, g
, e
->dot2
->x
, e
->dot2
->y
, &x2
, &y2
);
3302 if (line_colour
!= COL_BACKGROUND
) {
3303 /* (dx, dy) points roughly from (x1, y1) to (x2, y2).
3304 * The line is then "fattened" in a (roughly) perpendicular
3305 * direction to create a thin rectangle. */
3306 int dx
= (x1
> x2
) ?
-1 : ((x1
< x2
) ?
1 : 0);
3307 int dy
= (y1
> y2
) ?
-1 : ((y1
< y2
) ?
1 : 0);
3309 points
[0] = x1
+ dy
;
3310 points
[1] = y1
- dx
;
3311 points
[2] = x1
- dy
;
3312 points
[3] = y1
+ dx
;
3313 points
[4] = x2
- dy
;
3314 points
[5] = y2
+ dx
;
3315 points
[6] = x2
+ dy
;
3316 points
[7] = y2
- dx
;
3317 draw_polygon(dr
, points
, 4, line_colour
, line_colour
);
3320 /* Draw dots at ends of the line */
3321 draw_circle(dr
, x1
, y1
, 2, COL_FOREGROUND
, COL_FOREGROUND
);
3322 draw_circle(dr
, x2
, y2
, 2, COL_FOREGROUND
, COL_FOREGROUND
);
3324 draw_update(dr
, xmin
-2, ymin
-2, xmax
- xmin
+ 4, ymax
- ymin
+ 4);
3329 for (i
= 0; i
< g
->num_dots
; i
++) {
3330 grid_dot
*d
= g
->dots
+ i
;
3332 grid_to_screen(ds
, g
, d
->x
, d
->y
, &x
, &y
);
3333 draw_circle(dr
, x
, y
, 2, COL_FOREGROUND
, COL_FOREGROUND
);
3339 static float game_flash_length(game_state
*oldstate
, game_state
*newstate
,
3340 int dir
, game_ui
*ui
)
3342 if (!oldstate
->solved
&& newstate
->solved
&&
3343 !oldstate
->cheated
&& !newstate
->cheated
) {
3350 static void game_print_size(game_params
*params
, float *x
, float *y
)
3355 * I'll use 7mm "squares" by default.
3357 game_compute_size(params
, 700, &pw
, &ph
);
3362 static void game_print(drawing
*dr
, game_state
*state
, int tilesize
)
3364 int ink
= print_mono_colour(dr
, 0);
3366 game_drawstate ads
, *ds
= &ads
;
3367 grid
*g
= state
->game_grid
;
3369 game_set_size(dr
, ds
, NULL
, tilesize
);
3371 for (i
= 0; i
< g
->num_dots
; i
++) {
3373 grid_to_screen(ds
, g
, g
->dots
[i
].x
, g
->dots
[i
].y
, &x
, &y
);
3374 draw_circle(dr
, x
, y
, ds
->tilesize
/ 15, ink
, ink
);
3380 for (i
= 0; i
< g
->num_faces
; i
++) {
3381 grid_face
*f
= g
->faces
+ i
;
3382 int clue
= state
->clues
[i
];
3386 c
[0] = CLUE2CHAR(clue
);
3388 face_text_pos(ds
, g
, f
, &x
, &y
);
3390 FONT_VARIABLE
, ds
->tilesize
/ 2,
3391 ALIGN_VCENTRE
| ALIGN_HCENTRE
, ink
, c
);
3398 for (i
= 0; i
< g
->num_edges
; i
++) {
3399 int thickness
= (state
->lines
[i
] == LINE_YES
) ?
30 : 150;
3400 grid_edge
*e
= g
->edges
+ i
;
3402 grid_to_screen(ds
, g
, e
->dot1
->x
, e
->dot1
->y
, &x1
, &y1
);
3403 grid_to_screen(ds
, g
, e
->dot2
->x
, e
->dot2
->y
, &x2
, &y2
);
3404 if (state
->lines
[i
] == LINE_YES
)
3406 /* (dx, dy) points from (x1, y1) to (x2, y2).
3407 * The line is then "fattened" in a perpendicular
3408 * direction to create a thin rectangle. */
3409 double d
= sqrt(SQ((double)x1
- x2
) + SQ((double)y1
- y2
));
3410 double dx
= (x2
- x1
) / d
;
3411 double dy
= (y2
- y1
) / d
;
3414 dx
= (dx
* ds
->tilesize
) / thickness
;
3415 dy
= (dy
* ds
->tilesize
) / thickness
;
3416 points
[0] = x1
+ (int)dy
;
3417 points
[1] = y1
- (int)dx
;
3418 points
[2] = x1
- (int)dy
;
3419 points
[3] = y1
+ (int)dx
;
3420 points
[4] = x2
- (int)dy
;
3421 points
[5] = y2
+ (int)dx
;
3422 points
[6] = x2
+ (int)dy
;
3423 points
[7] = y2
- (int)dx
;
3424 draw_polygon(dr
, points
, 4, ink
, ink
);
3428 /* Draw a dotted line */
3431 for (j
= 1; j
< divisions
; j
++) {
3432 /* Weighted average */
3433 int x
= (x1
* (divisions
-j
) + x2
* j
) / divisions
;
3434 int y
= (y1
* (divisions
-j
) + y2
* j
) / divisions
;
3435 draw_circle(dr
, x
, y
, ds
->tilesize
/ thickness
, ink
, ink
);
3442 #define thegame loopy
3445 const struct game thegame
= {
3446 "Loopy", "games.loopy", "loopy",
3453 TRUE
, game_configure
, custom_params
,
3461 TRUE
, game_can_format_as_text_now
, game_text_format
,
3469 PREFERRED_TILE_SIZE
, game_compute_size
, game_set_size
,
3472 game_free_drawstate
,
3476 TRUE
, FALSE
, game_print_size
, game_print
,
3477 FALSE
/* wants_statusbar */,
3478 FALSE
, game_timing_state
,
3479 0, /* mouse_priorities */