Lambros points out that trying to generate a 3x3 Cairo Easy grid
[sgt/puzzles] / loopy.c
1 /*
2 * loopy.c:
3 *
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
8 *
9 * vim: set shiftwidth=4 :set textwidth=80:
10 */
11
12 /*
13 * Possible future solver enhancements:
14 *
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
32 * exterior "face".
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
49 * face-edsf class.
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
53 * done.
54 *
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
67 * the solver.
68 *
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.
72 */
73
74 #include <stdio.h>
75 #include <stdlib.h>
76 #include <string.h>
77 #include <assert.h>
78 #include <ctype.h>
79 #include <math.h>
80
81 #include "puzzles.h"
82 #include "tree234.h"
83 #include "grid.h"
84
85 /* Debugging options */
86
87 /*
88 #define DEBUG_CACHES
89 #define SHOW_WORKING
90 #define DEBUG_DLINES
91 */
92
93 /* ----------------------------------------------------------------------
94 * Struct, enum and function declarations
95 */
96
97 enum {
98 COL_BACKGROUND,
99 COL_FOREGROUND,
100 COL_LINEUNKNOWN,
101 COL_HIGHLIGHT,
102 COL_MISTAKE,
103 COL_SATISFIED,
104 NCOLOURS
105 };
106
107 struct game_state {
108 grid *game_grid;
109
110 /* Put -1 in a face that doesn't get a clue */
111 signed char *clues;
112
113 /* Array of line states, to store whether each line is
114 * YES, NO or UNKNOWN */
115 char *lines;
116
117 unsigned char *line_errors;
118
119 int solved;
120 int cheated;
121
122 /* Used in game_text_format(), so that it knows what type of
123 * grid it's trying to render as ASCII text. */
124 int grid_type;
125 };
126
127 enum solver_status {
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 */
132 };
133
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 */
139 char *dlines;
140 } normal_mode_state;
141
142 typedef struct hard {
143 int *linedsf;
144 } hard_mode_state;
145
146 typedef struct solver_state {
147 game_state *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 */
151 int *looplen;
152
153 /* caches */
154 char *dot_yes_count;
155 char *dot_no_count;
156 char *face_yes_count;
157 char *face_no_count;
158 char *dot_solved, *face_solved;
159 int *dotdsf;
160
161 normal_mode_state *normal;
162 hard_mode_state *hard;
163 } solver_state;
164
165 /*
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.
168 */
169
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) };
186
187 struct game_params {
188 int w, h;
189 int diff;
190 int type;
191
192 /* Grid generation is expensive, so keep a (ref-counted) reference to the
193 * grid for these parameters, and only generate when required. */
194 grid *game_grid;
195 };
196
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 };
203
204 #define OPP(line_state) \
205 (2 - line_state)
206
207
208 struct game_drawstate {
209 int started;
210 int tilesize;
211 int flashing;
212 char *lines;
213 char *clue_error;
214 char *clue_satisfied;
215 };
216
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,
221 int diff);
222
223 #ifdef DEBUG_CACHES
224 static void check_caches(const solver_state* sstate);
225 #else
226 #define check_caches(s)
227 #endif
228
229 /* ------- List of grid generators ------- */
230 #define GRIDLIST(A) \
231 A(Squares,grid_new_square,3,3) \
232 A(Triangular,grid_new_triangular,3,3) \
233 A(Honeycomb,grid_new_honeycomb,3,3) \
234 A(Snub-Square,grid_new_snubsquare,3,3) \
235 A(Cairo,grid_new_cairo,3,4) \
236 A(Great-Hexagonal,grid_new_greathexagonal,3,3) \
237 A(Octagonal,grid_new_octagonal,3,3) \
238 A(Kites,grid_new_kites,3,3)
239
240 #define GRID_NAME(title,fn,amin,omin) #title,
241 #define GRID_CONFIG(title,fn,amin,omin) ":" #title
242 #define GRID_FN(title,fn,amin,omin) &fn,
243 #define GRID_SIZES(title,fn,amin,omin) \
244 {amin, omin, \
245 "Width and height for this grid type must both be at least " #amin, \
246 "At least one of width and height for this grid type must be at least " #omin,},
247 static char const *const gridnames[] = { GRIDLIST(GRID_NAME) };
248 #define GRID_CONFIGS GRIDLIST(GRID_CONFIG)
249 static grid * (*(grid_fns[]))(int w, int h) = { GRIDLIST(GRID_FN) };
250 #define NUM_GRID_TYPES (sizeof(grid_fns) / sizeof(grid_fns[0]))
251 static const struct {
252 int amin, omin;
253 char *aerr, *oerr;
254 } grid_size_limits[] = { GRIDLIST(GRID_SIZES) };
255
256 /* Generates a (dynamically allocated) new grid, according to the
257 * type and size requested in params. Does nothing if the grid is already
258 * generated. The allocated grid is owned by the params object, and will be
259 * freed in free_params(). */
260 static void params_generate_grid(game_params *params)
261 {
262 if (!params->game_grid) {
263 params->game_grid = grid_fns[params->type](params->w, params->h);
264 }
265 }
266
267 /* ----------------------------------------------------------------------
268 * Preprocessor magic
269 */
270
271 /* General constants */
272 #define PREFERRED_TILE_SIZE 32
273 #define BORDER(tilesize) ((tilesize) / 2)
274 #define FLASH_TIME 0.5F
275
276 #define BIT_SET(field, bit) ((field) & (1<<(bit)))
277
278 #define SET_BIT(field, bit) (BIT_SET(field, bit) ? FALSE : \
279 ((field) |= (1<<(bit)), TRUE))
280
281 #define CLEAR_BIT(field, bit) (BIT_SET(field, bit) ? \
282 ((field) &= ~(1<<(bit)), TRUE) : FALSE)
283
284 #define CLUE2CHAR(c) \
285 ((c < 0) ? ' ' : c + '0')
286
287 /* ----------------------------------------------------------------------
288 * General struct manipulation and other straightforward code
289 */
290
291 static game_state *dup_game(game_state *state)
292 {
293 game_state *ret = snew(game_state);
294
295 ret->game_grid = state->game_grid;
296 ret->game_grid->refcount++;
297
298 ret->solved = state->solved;
299 ret->cheated = state->cheated;
300
301 ret->clues = snewn(state->game_grid->num_faces, signed char);
302 memcpy(ret->clues, state->clues, state->game_grid->num_faces);
303
304 ret->lines = snewn(state->game_grid->num_edges, char);
305 memcpy(ret->lines, state->lines, state->game_grid->num_edges);
306
307 ret->line_errors = snewn(state->game_grid->num_edges, unsigned char);
308 memcpy(ret->line_errors, state->line_errors, state->game_grid->num_edges);
309
310 ret->grid_type = state->grid_type;
311 return ret;
312 }
313
314 static void free_game(game_state *state)
315 {
316 if (state) {
317 grid_free(state->game_grid);
318 sfree(state->clues);
319 sfree(state->lines);
320 sfree(state->line_errors);
321 sfree(state);
322 }
323 }
324
325 static solver_state *new_solver_state(game_state *state, int diff) {
326 int i;
327 int num_dots = state->game_grid->num_dots;
328 int num_faces = state->game_grid->num_faces;
329 int num_edges = state->game_grid->num_edges;
330 solver_state *ret = snew(solver_state);
331
332 ret->state = dup_game(state);
333
334 ret->solver_status = SOLVER_INCOMPLETE;
335
336 ret->dotdsf = snew_dsf(num_dots);
337 ret->looplen = snewn(num_dots, int);
338
339 for (i = 0; i < num_dots; i++) {
340 ret->looplen[i] = 1;
341 }
342
343 ret->dot_solved = snewn(num_dots, char);
344 ret->face_solved = snewn(num_faces, char);
345 memset(ret->dot_solved, FALSE, num_dots);
346 memset(ret->face_solved, FALSE, num_faces);
347
348 ret->dot_yes_count = snewn(num_dots, char);
349 memset(ret->dot_yes_count, 0, num_dots);
350 ret->dot_no_count = snewn(num_dots, char);
351 memset(ret->dot_no_count, 0, num_dots);
352 ret->face_yes_count = snewn(num_faces, char);
353 memset(ret->face_yes_count, 0, num_faces);
354 ret->face_no_count = snewn(num_faces, char);
355 memset(ret->face_no_count, 0, num_faces);
356
357 if (diff < DIFF_NORMAL) {
358 ret->normal = NULL;
359 } else {
360 ret->normal = snew(normal_mode_state);
361 ret->normal->dlines = snewn(2*num_edges, char);
362 memset(ret->normal->dlines, 0, 2*num_edges);
363 }
364
365 if (diff < DIFF_HARD) {
366 ret->hard = NULL;
367 } else {
368 ret->hard = snew(hard_mode_state);
369 ret->hard->linedsf = snew_dsf(state->game_grid->num_edges);
370 }
371
372 return ret;
373 }
374
375 static void free_solver_state(solver_state *sstate) {
376 if (sstate) {
377 free_game(sstate->state);
378 sfree(sstate->dotdsf);
379 sfree(sstate->looplen);
380 sfree(sstate->dot_solved);
381 sfree(sstate->face_solved);
382 sfree(sstate->dot_yes_count);
383 sfree(sstate->dot_no_count);
384 sfree(sstate->face_yes_count);
385 sfree(sstate->face_no_count);
386
387 if (sstate->normal) {
388 sfree(sstate->normal->dlines);
389 sfree(sstate->normal);
390 }
391
392 if (sstate->hard) {
393 sfree(sstate->hard->linedsf);
394 sfree(sstate->hard);
395 }
396
397 sfree(sstate);
398 }
399 }
400
401 static solver_state *dup_solver_state(const solver_state *sstate) {
402 game_state *state = sstate->state;
403 int num_dots = state->game_grid->num_dots;
404 int num_faces = state->game_grid->num_faces;
405 int num_edges = state->game_grid->num_edges;
406 solver_state *ret = snew(solver_state);
407
408 ret->state = state = dup_game(sstate->state);
409
410 ret->solver_status = sstate->solver_status;
411
412 ret->dotdsf = snewn(num_dots, int);
413 ret->looplen = snewn(num_dots, int);
414 memcpy(ret->dotdsf, sstate->dotdsf,
415 num_dots * sizeof(int));
416 memcpy(ret->looplen, sstate->looplen,
417 num_dots * sizeof(int));
418
419 ret->dot_solved = snewn(num_dots, char);
420 ret->face_solved = snewn(num_faces, char);
421 memcpy(ret->dot_solved, sstate->dot_solved, num_dots);
422 memcpy(ret->face_solved, sstate->face_solved, num_faces);
423
424 ret->dot_yes_count = snewn(num_dots, char);
425 memcpy(ret->dot_yes_count, sstate->dot_yes_count, num_dots);
426 ret->dot_no_count = snewn(num_dots, char);
427 memcpy(ret->dot_no_count, sstate->dot_no_count, num_dots);
428
429 ret->face_yes_count = snewn(num_faces, char);
430 memcpy(ret->face_yes_count, sstate->face_yes_count, num_faces);
431 ret->face_no_count = snewn(num_faces, char);
432 memcpy(ret->face_no_count, sstate->face_no_count, num_faces);
433
434 if (sstate->normal) {
435 ret->normal = snew(normal_mode_state);
436 ret->normal->dlines = snewn(2*num_edges, char);
437 memcpy(ret->normal->dlines, sstate->normal->dlines,
438 2*num_edges);
439 } else {
440 ret->normal = NULL;
441 }
442
443 if (sstate->hard) {
444 ret->hard = snew(hard_mode_state);
445 ret->hard->linedsf = snewn(num_edges, int);
446 memcpy(ret->hard->linedsf, sstate->hard->linedsf,
447 num_edges * sizeof(int));
448 } else {
449 ret->hard = NULL;
450 }
451
452 return ret;
453 }
454
455 static game_params *default_params(void)
456 {
457 game_params *ret = snew(game_params);
458
459 #ifdef SLOW_SYSTEM
460 ret->h = 7;
461 ret->w = 7;
462 #else
463 ret->h = 10;
464 ret->w = 10;
465 #endif
466 ret->diff = DIFF_EASY;
467 ret->type = 0;
468
469 ret->game_grid = NULL;
470
471 return ret;
472 }
473
474 static game_params *dup_params(game_params *params)
475 {
476 game_params *ret = snew(game_params);
477
478 *ret = *params; /* structure copy */
479 if (ret->game_grid) {
480 ret->game_grid->refcount++;
481 }
482 return ret;
483 }
484
485 static const game_params presets[] = {
486 #ifdef SMALL_SCREEN
487 { 7, 7, DIFF_EASY, 0, NULL },
488 { 7, 7, DIFF_NORMAL, 0, NULL },
489 { 7, 7, DIFF_HARD, 0, NULL },
490 { 7, 7, DIFF_HARD, 1, NULL },
491 { 7, 7, DIFF_HARD, 2, NULL },
492 { 5, 5, DIFF_HARD, 3, NULL },
493 { 7, 7, DIFF_HARD, 4, NULL },
494 { 5, 4, DIFF_HARD, 5, NULL },
495 { 5, 5, DIFF_HARD, 6, NULL },
496 { 5, 5, DIFF_HARD, 7, NULL },
497 #else
498 { 7, 7, DIFF_EASY, 0, NULL },
499 { 10, 10, DIFF_EASY, 0, NULL },
500 { 7, 7, DIFF_NORMAL, 0, NULL },
501 { 10, 10, DIFF_NORMAL, 0, NULL },
502 { 7, 7, DIFF_HARD, 0, NULL },
503 { 10, 10, DIFF_HARD, 0, NULL },
504 { 10, 10, DIFF_HARD, 1, NULL },
505 { 12, 10, DIFF_HARD, 2, NULL },
506 { 7, 7, DIFF_HARD, 3, NULL },
507 { 9, 9, DIFF_HARD, 4, NULL },
508 { 5, 4, DIFF_HARD, 5, NULL },
509 { 7, 7, DIFF_HARD, 6, NULL },
510 { 5, 5, DIFF_HARD, 7, NULL },
511 #endif
512 };
513
514 static int game_fetch_preset(int i, char **name, game_params **params)
515 {
516 game_params *tmppar;
517 char buf[80];
518
519 if (i < 0 || i >= lenof(presets))
520 return FALSE;
521
522 tmppar = snew(game_params);
523 *tmppar = presets[i];
524 *params = tmppar;
525 sprintf(buf, "%dx%d %s - %s", tmppar->h, tmppar->w,
526 gridnames[tmppar->type], diffnames[tmppar->diff]);
527 *name = dupstr(buf);
528
529 return TRUE;
530 }
531
532 static void free_params(game_params *params)
533 {
534 if (params->game_grid) {
535 grid_free(params->game_grid);
536 }
537 sfree(params);
538 }
539
540 static void decode_params(game_params *params, char const *string)
541 {
542 if (params->game_grid) {
543 grid_free(params->game_grid);
544 params->game_grid = NULL;
545 }
546 params->h = params->w = atoi(string);
547 params->diff = DIFF_EASY;
548 while (*string && isdigit((unsigned char)*string)) string++;
549 if (*string == 'x') {
550 string++;
551 params->h = atoi(string);
552 while (*string && isdigit((unsigned char)*string)) string++;
553 }
554 if (*string == 't') {
555 string++;
556 params->type = atoi(string);
557 while (*string && isdigit((unsigned char)*string)) string++;
558 }
559 if (*string == 'd') {
560 int i;
561 string++;
562 for (i = 0; i < DIFF_MAX; i++)
563 if (*string == diffchars[i])
564 params->diff = i;
565 if (*string) string++;
566 }
567 }
568
569 static char *encode_params(game_params *params, int full)
570 {
571 char str[80];
572 sprintf(str, "%dx%dt%d", params->w, params->h, params->type);
573 if (full)
574 sprintf(str + strlen(str), "d%c", diffchars[params->diff]);
575 return dupstr(str);
576 }
577
578 static config_item *game_configure(game_params *params)
579 {
580 config_item *ret;
581 char buf[80];
582
583 ret = snewn(5, config_item);
584
585 ret[0].name = "Width";
586 ret[0].type = C_STRING;
587 sprintf(buf, "%d", params->w);
588 ret[0].sval = dupstr(buf);
589 ret[0].ival = 0;
590
591 ret[1].name = "Height";
592 ret[1].type = C_STRING;
593 sprintf(buf, "%d", params->h);
594 ret[1].sval = dupstr(buf);
595 ret[1].ival = 0;
596
597 ret[2].name = "Grid type";
598 ret[2].type = C_CHOICES;
599 ret[2].sval = GRID_CONFIGS;
600 ret[2].ival = params->type;
601
602 ret[3].name = "Difficulty";
603 ret[3].type = C_CHOICES;
604 ret[3].sval = DIFFCONFIG;
605 ret[3].ival = params->diff;
606
607 ret[4].name = NULL;
608 ret[4].type = C_END;
609 ret[4].sval = NULL;
610 ret[4].ival = 0;
611
612 return ret;
613 }
614
615 static game_params *custom_params(config_item *cfg)
616 {
617 game_params *ret = snew(game_params);
618
619 ret->w = atoi(cfg[0].sval);
620 ret->h = atoi(cfg[1].sval);
621 ret->type = cfg[2].ival;
622 ret->diff = cfg[3].ival;
623
624 ret->game_grid = NULL;
625 return ret;
626 }
627
628 static char *validate_params(game_params *params, int full)
629 {
630 if (params->type < 0 || params->type >= NUM_GRID_TYPES)
631 return "Illegal grid type";
632 if (params->w < grid_size_limits[params->type].amin ||
633 params->h < grid_size_limits[params->type].amin)
634 return grid_size_limits[params->type].aerr;
635 if (params->w < grid_size_limits[params->type].omin &&
636 params->h < grid_size_limits[params->type].omin)
637 return grid_size_limits[params->type].oerr;
638
639 /*
640 * This shouldn't be able to happen at all, since decode_params
641 * and custom_params will never generate anything that isn't
642 * within range.
643 */
644 assert(params->diff < DIFF_MAX);
645
646 return NULL;
647 }
648
649 /* Returns a newly allocated string describing the current puzzle */
650 static char *state_to_text(const game_state *state)
651 {
652 grid *g = state->game_grid;
653 char *retval;
654 int num_faces = g->num_faces;
655 char *description = snewn(num_faces + 1, char);
656 char *dp = description;
657 int empty_count = 0;
658 int i;
659
660 for (i = 0; i < num_faces; i++) {
661 if (state->clues[i] < 0) {
662 if (empty_count > 25) {
663 dp += sprintf(dp, "%c", (int)(empty_count + 'a' - 1));
664 empty_count = 0;
665 }
666 empty_count++;
667 } else {
668 if (empty_count) {
669 dp += sprintf(dp, "%c", (int)(empty_count + 'a' - 1));
670 empty_count = 0;
671 }
672 dp += sprintf(dp, "%c", (int)CLUE2CHAR(state->clues[i]));
673 }
674 }
675
676 if (empty_count)
677 dp += sprintf(dp, "%c", (int)(empty_count + 'a' - 1));
678
679 retval = dupstr(description);
680 sfree(description);
681
682 return retval;
683 }
684
685 /* We require that the params pass the test in validate_params and that the
686 * description fills the entire game area */
687 static char *validate_desc(game_params *params, char *desc)
688 {
689 int count = 0;
690 grid *g;
691 params_generate_grid(params);
692 g = params->game_grid;
693
694 for (; *desc; ++desc) {
695 if (*desc >= '0' && *desc <= '9') {
696 count++;
697 continue;
698 }
699 if (*desc >= 'a') {
700 count += *desc - 'a' + 1;
701 continue;
702 }
703 return "Unknown character in description";
704 }
705
706 if (count < g->num_faces)
707 return "Description too short for board size";
708 if (count > g->num_faces)
709 return "Description too long for board size";
710
711 return NULL;
712 }
713
714 /* Sums the lengths of the numbers in range [0,n) */
715 /* See equivalent function in solo.c for justification of this. */
716 static int len_0_to_n(int n)
717 {
718 int len = 1; /* Counting 0 as a bit of a special case */
719 int i;
720
721 for (i = 1; i < n; i *= 10) {
722 len += max(n - i, 0);
723 }
724
725 return len;
726 }
727
728 static char *encode_solve_move(const game_state *state)
729 {
730 int len;
731 char *ret, *p;
732 int i;
733 int num_edges = state->game_grid->num_edges;
734
735 /* This is going to return a string representing the moves needed to set
736 * every line in a grid to be the same as the ones in 'state'. The exact
737 * length of this string is predictable. */
738
739 len = 1; /* Count the 'S' prefix */
740 /* Numbers in all lines */
741 len += len_0_to_n(num_edges);
742 /* For each line we also have a letter */
743 len += num_edges;
744
745 ret = snewn(len + 1, char);
746 p = ret;
747
748 p += sprintf(p, "S");
749
750 for (i = 0; i < num_edges; i++) {
751 switch (state->lines[i]) {
752 case LINE_YES:
753 p += sprintf(p, "%dy", i);
754 break;
755 case LINE_NO:
756 p += sprintf(p, "%dn", i);
757 break;
758 }
759 }
760
761 /* No point in doing sums like that if they're going to be wrong */
762 assert(strlen(ret) <= (size_t)len);
763 return ret;
764 }
765
766 static game_ui *new_ui(game_state *state)
767 {
768 return NULL;
769 }
770
771 static void free_ui(game_ui *ui)
772 {
773 }
774
775 static char *encode_ui(game_ui *ui)
776 {
777 return NULL;
778 }
779
780 static void decode_ui(game_ui *ui, char *encoding)
781 {
782 }
783
784 static void game_changed_state(game_ui *ui, game_state *oldstate,
785 game_state *newstate)
786 {
787 }
788
789 static void game_compute_size(game_params *params, int tilesize,
790 int *x, int *y)
791 {
792 grid *g;
793 int grid_width, grid_height, rendered_width, rendered_height;
794
795 params_generate_grid(params);
796 g = params->game_grid;
797 grid_width = g->highest_x - g->lowest_x;
798 grid_height = g->highest_y - g->lowest_y;
799 /* multiply first to minimise rounding error on integer division */
800 rendered_width = grid_width * tilesize / g->tilesize;
801 rendered_height = grid_height * tilesize / g->tilesize;
802 *x = rendered_width + 2 * BORDER(tilesize) + 1;
803 *y = rendered_height + 2 * BORDER(tilesize) + 1;
804 }
805
806 static void game_set_size(drawing *dr, game_drawstate *ds,
807 game_params *params, int tilesize)
808 {
809 ds->tilesize = tilesize;
810 }
811
812 static float *game_colours(frontend *fe, int *ncolours)
813 {
814 float *ret = snewn(4 * NCOLOURS, float);
815
816 frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
817
818 ret[COL_FOREGROUND * 3 + 0] = 0.0F;
819 ret[COL_FOREGROUND * 3 + 1] = 0.0F;
820 ret[COL_FOREGROUND * 3 + 2] = 0.0F;
821
822 ret[COL_LINEUNKNOWN * 3 + 0] = 0.8F;
823 ret[COL_LINEUNKNOWN * 3 + 1] = 0.8F;
824 ret[COL_LINEUNKNOWN * 3 + 2] = 0.0F;
825
826 ret[COL_HIGHLIGHT * 3 + 0] = 1.0F;
827 ret[COL_HIGHLIGHT * 3 + 1] = 1.0F;
828 ret[COL_HIGHLIGHT * 3 + 2] = 1.0F;
829
830 ret[COL_MISTAKE * 3 + 0] = 1.0F;
831 ret[COL_MISTAKE * 3 + 1] = 0.0F;
832 ret[COL_MISTAKE * 3 + 2] = 0.0F;
833
834 ret[COL_SATISFIED * 3 + 0] = 0.0F;
835 ret[COL_SATISFIED * 3 + 1] = 0.0F;
836 ret[COL_SATISFIED * 3 + 2] = 0.0F;
837
838 *ncolours = NCOLOURS;
839 return ret;
840 }
841
842 static game_drawstate *game_new_drawstate(drawing *dr, game_state *state)
843 {
844 struct game_drawstate *ds = snew(struct game_drawstate);
845 int num_faces = state->game_grid->num_faces;
846 int num_edges = state->game_grid->num_edges;
847
848 ds->tilesize = 0;
849 ds->started = 0;
850 ds->lines = snewn(num_edges, char);
851 ds->clue_error = snewn(num_faces, char);
852 ds->clue_satisfied = snewn(num_faces, char);
853 ds->flashing = 0;
854
855 memset(ds->lines, LINE_UNKNOWN, num_edges);
856 memset(ds->clue_error, 0, num_faces);
857 memset(ds->clue_satisfied, 0, num_faces);
858
859 return ds;
860 }
861
862 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
863 {
864 sfree(ds->clue_error);
865 sfree(ds->clue_satisfied);
866 sfree(ds->lines);
867 sfree(ds);
868 }
869
870 static int game_timing_state(game_state *state, game_ui *ui)
871 {
872 return TRUE;
873 }
874
875 static float game_anim_length(game_state *oldstate, game_state *newstate,
876 int dir, game_ui *ui)
877 {
878 return 0.0F;
879 }
880
881 static int game_can_format_as_text_now(game_params *params)
882 {
883 if (params->type != 0)
884 return FALSE;
885 return TRUE;
886 }
887
888 static char *game_text_format(game_state *state)
889 {
890 int w, h, W, H;
891 int x, y, i;
892 int cell_size;
893 char *ret;
894 grid *g = state->game_grid;
895 grid_face *f;
896
897 assert(state->grid_type == 0);
898
899 /* Work out the basic size unit */
900 f = g->faces; /* first face */
901 assert(f->order == 4);
902 /* The dots are ordered clockwise, so the two opposite
903 * corners are guaranteed to span the square */
904 cell_size = abs(f->dots[0]->x - f->dots[2]->x);
905
906 w = (g->highest_x - g->lowest_x) / cell_size;
907 h = (g->highest_y - g->lowest_y) / cell_size;
908
909 /* Create a blank "canvas" to "draw" on */
910 W = 2 * w + 2;
911 H = 2 * h + 1;
912 ret = snewn(W * H + 1, char);
913 for (y = 0; y < H; y++) {
914 for (x = 0; x < W-1; x++) {
915 ret[y*W + x] = ' ';
916 }
917 ret[y*W + W-1] = '\n';
918 }
919 ret[H*W] = '\0';
920
921 /* Fill in edge info */
922 for (i = 0; i < g->num_edges; i++) {
923 grid_edge *e = g->edges + i;
924 /* Cell coordinates, from (0,0) to (w-1,h-1) */
925 int x1 = (e->dot1->x - g->lowest_x) / cell_size;
926 int x2 = (e->dot2->x - g->lowest_x) / cell_size;
927 int y1 = (e->dot1->y - g->lowest_y) / cell_size;
928 int y2 = (e->dot2->y - g->lowest_y) / cell_size;
929 /* Midpoint, in canvas coordinates (canvas coordinates are just twice
930 * cell coordinates) */
931 x = x1 + x2;
932 y = y1 + y2;
933 switch (state->lines[i]) {
934 case LINE_YES:
935 ret[y*W + x] = (y1 == y2) ? '-' : '|';
936 break;
937 case LINE_NO:
938 ret[y*W + x] = 'x';
939 break;
940 case LINE_UNKNOWN:
941 break; /* already a space */
942 default:
943 assert(!"Illegal line state");
944 }
945 }
946
947 /* Fill in clues */
948 for (i = 0; i < g->num_faces; i++) {
949 int x1, x2, y1, y2;
950
951 f = g->faces + i;
952 assert(f->order == 4);
953 /* Cell coordinates, from (0,0) to (w-1,h-1) */
954 x1 = (f->dots[0]->x - g->lowest_x) / cell_size;
955 x2 = (f->dots[2]->x - g->lowest_x) / cell_size;
956 y1 = (f->dots[0]->y - g->lowest_y) / cell_size;
957 y2 = (f->dots[2]->y - g->lowest_y) / cell_size;
958 /* Midpoint, in canvas coordinates */
959 x = x1 + x2;
960 y = y1 + y2;
961 ret[y*W + x] = CLUE2CHAR(state->clues[i]);
962 }
963 return ret;
964 }
965
966 /* ----------------------------------------------------------------------
967 * Debug code
968 */
969
970 #ifdef DEBUG_CACHES
971 static void check_caches(const solver_state* sstate)
972 {
973 int i;
974 const game_state *state = sstate->state;
975 const grid *g = state->game_grid;
976
977 for (i = 0; i < g->num_dots; i++) {
978 assert(dot_order(state, i, LINE_YES) == sstate->dot_yes_count[i]);
979 assert(dot_order(state, i, LINE_NO) == sstate->dot_no_count[i]);
980 }
981
982 for (i = 0; i < g->num_faces; i++) {
983 assert(face_order(state, i, LINE_YES) == sstate->face_yes_count[i]);
984 assert(face_order(state, i, LINE_NO) == sstate->face_no_count[i]);
985 }
986 }
987
988 #if 0
989 #define check_caches(s) \
990 do { \
991 fprintf(stderr, "check_caches at line %d\n", __LINE__); \
992 check_caches(s); \
993 } while (0)
994 #endif
995 #endif /* DEBUG_CACHES */
996
997 /* ----------------------------------------------------------------------
998 * Solver utility functions
999 */
1000
1001 /* Sets the line (with index i) to the new state 'line_new', and updates
1002 * the cached counts of any affected faces and dots.
1003 * Returns TRUE if this actually changed the line's state. */
1004 static int solver_set_line(solver_state *sstate, int i,
1005 enum line_state line_new
1006 #ifdef SHOW_WORKING
1007 , const char *reason
1008 #endif
1009 )
1010 {
1011 game_state *state = sstate->state;
1012 grid *g;
1013 grid_edge *e;
1014
1015 assert(line_new != LINE_UNKNOWN);
1016
1017 check_caches(sstate);
1018
1019 if (state->lines[i] == line_new) {
1020 return FALSE; /* nothing changed */
1021 }
1022 state->lines[i] = line_new;
1023
1024 #ifdef SHOW_WORKING
1025 fprintf(stderr, "solver: set line [%d] to %s (%s)\n",
1026 i, line_new == LINE_YES ? "YES" : "NO",
1027 reason);
1028 #endif
1029
1030 g = state->game_grid;
1031 e = g->edges + i;
1032
1033 /* Update the cache for both dots and both faces affected by this. */
1034 if (line_new == LINE_YES) {
1035 sstate->dot_yes_count[e->dot1 - g->dots]++;
1036 sstate->dot_yes_count[e->dot2 - g->dots]++;
1037 if (e->face1) {
1038 sstate->face_yes_count[e->face1 - g->faces]++;
1039 }
1040 if (e->face2) {
1041 sstate->face_yes_count[e->face2 - g->faces]++;
1042 }
1043 } else {
1044 sstate->dot_no_count[e->dot1 - g->dots]++;
1045 sstate->dot_no_count[e->dot2 - g->dots]++;
1046 if (e->face1) {
1047 sstate->face_no_count[e->face1 - g->faces]++;
1048 }
1049 if (e->face2) {
1050 sstate->face_no_count[e->face2 - g->faces]++;
1051 }
1052 }
1053
1054 check_caches(sstate);
1055 return TRUE;
1056 }
1057
1058 #ifdef SHOW_WORKING
1059 #define solver_set_line(a, b, c) \
1060 solver_set_line(a, b, c, __FUNCTION__)
1061 #endif
1062
1063 /*
1064 * Merge two dots due to the existence of an edge between them.
1065 * Updates the dsf tracking equivalence classes, and keeps track of
1066 * the length of path each dot is currently a part of.
1067 * Returns TRUE if the dots were already linked, ie if they are part of a
1068 * closed loop, and false otherwise.
1069 */
1070 static int merge_dots(solver_state *sstate, int edge_index)
1071 {
1072 int i, j, len;
1073 grid *g = sstate->state->game_grid;
1074 grid_edge *e = g->edges + edge_index;
1075
1076 i = e->dot1 - g->dots;
1077 j = e->dot2 - g->dots;
1078
1079 i = dsf_canonify(sstate->dotdsf, i);
1080 j = dsf_canonify(sstate->dotdsf, j);
1081
1082 if (i == j) {
1083 return TRUE;
1084 } else {
1085 len = sstate->looplen[i] + sstate->looplen[j];
1086 dsf_merge(sstate->dotdsf, i, j);
1087 i = dsf_canonify(sstate->dotdsf, i);
1088 sstate->looplen[i] = len;
1089 return FALSE;
1090 }
1091 }
1092
1093 /* Merge two lines because the solver has deduced that they must be either
1094 * identical or opposite. Returns TRUE if this is new information, otherwise
1095 * FALSE. */
1096 static int merge_lines(solver_state *sstate, int i, int j, int inverse
1097 #ifdef SHOW_WORKING
1098 , const char *reason
1099 #endif
1100 )
1101 {
1102 int inv_tmp;
1103
1104 assert(i < sstate->state->game_grid->num_edges);
1105 assert(j < sstate->state->game_grid->num_edges);
1106
1107 i = edsf_canonify(sstate->hard->linedsf, i, &inv_tmp);
1108 inverse ^= inv_tmp;
1109 j = edsf_canonify(sstate->hard->linedsf, j, &inv_tmp);
1110 inverse ^= inv_tmp;
1111
1112 edsf_merge(sstate->hard->linedsf, i, j, inverse);
1113
1114 #ifdef SHOW_WORKING
1115 if (i != j) {
1116 fprintf(stderr, "%s [%d] [%d] %s(%s)\n",
1117 __FUNCTION__, i, j,
1118 inverse ? "inverse " : "", reason);
1119 }
1120 #endif
1121 return (i != j);
1122 }
1123
1124 #ifdef SHOW_WORKING
1125 #define merge_lines(a, b, c, d) \
1126 merge_lines(a, b, c, d, __FUNCTION__)
1127 #endif
1128
1129 /* Count the number of lines of a particular type currently going into the
1130 * given dot. */
1131 static int dot_order(const game_state* state, int dot, char line_type)
1132 {
1133 int n = 0;
1134 grid *g = state->game_grid;
1135 grid_dot *d = g->dots + dot;
1136 int i;
1137
1138 for (i = 0; i < d->order; i++) {
1139 grid_edge *e = d->edges[i];
1140 if (state->lines[e - g->edges] == line_type)
1141 ++n;
1142 }
1143 return n;
1144 }
1145
1146 /* Count the number of lines of a particular type currently surrounding the
1147 * given face */
1148 static int face_order(const game_state* state, int face, char line_type)
1149 {
1150 int n = 0;
1151 grid *g = state->game_grid;
1152 grid_face *f = g->faces + face;
1153 int i;
1154
1155 for (i = 0; i < f->order; i++) {
1156 grid_edge *e = f->edges[i];
1157 if (state->lines[e - g->edges] == line_type)
1158 ++n;
1159 }
1160 return n;
1161 }
1162
1163 /* Set all lines bordering a dot of type old_type to type new_type
1164 * Return value tells caller whether this function actually did anything */
1165 static int dot_setall(solver_state *sstate, int dot,
1166 char old_type, char new_type)
1167 {
1168 int retval = FALSE, r;
1169 game_state *state = sstate->state;
1170 grid *g;
1171 grid_dot *d;
1172 int i;
1173
1174 if (old_type == new_type)
1175 return FALSE;
1176
1177 g = state->game_grid;
1178 d = g->dots + dot;
1179
1180 for (i = 0; i < d->order; i++) {
1181 int line_index = d->edges[i] - g->edges;
1182 if (state->lines[line_index] == old_type) {
1183 r = solver_set_line(sstate, line_index, new_type);
1184 assert(r == TRUE);
1185 retval = TRUE;
1186 }
1187 }
1188 return retval;
1189 }
1190
1191 /* Set all lines bordering a face of type old_type to type new_type */
1192 static int face_setall(solver_state *sstate, int face,
1193 char old_type, char new_type)
1194 {
1195 int retval = FALSE, r;
1196 game_state *state = sstate->state;
1197 grid *g;
1198 grid_face *f;
1199 int i;
1200
1201 if (old_type == new_type)
1202 return FALSE;
1203
1204 g = state->game_grid;
1205 f = g->faces + face;
1206
1207 for (i = 0; i < f->order; i++) {
1208 int line_index = f->edges[i] - g->edges;
1209 if (state->lines[line_index] == old_type) {
1210 r = solver_set_line(sstate, line_index, new_type);
1211 assert(r == TRUE);
1212 retval = TRUE;
1213 }
1214 }
1215 return retval;
1216 }
1217
1218 /* ----------------------------------------------------------------------
1219 * Loop generation and clue removal
1220 */
1221
1222 /* We're going to store a list of current candidate faces for lighting.
1223 * Each face gets a 'score', which tells us how adding that face right
1224 * now would affect the length of the solution loop. We're trying to
1225 * maximise that quantity so will bias our random selection of faces to
1226 * light towards those with high scores */
1227 struct face {
1228 int score;
1229 unsigned long random;
1230 grid_face *f;
1231 };
1232
1233 static int get_face_cmpfn(void *v1, void *v2)
1234 {
1235 struct face *f1 = v1;
1236 struct face *f2 = v2;
1237 /* These grid_face pointers always point into the same list of
1238 * 'grid_face's, so it's valid to subtract them. */
1239 return f1->f - f2->f;
1240 }
1241
1242 static int face_sort_cmpfn(void *v1, void *v2)
1243 {
1244 struct face *f1 = v1;
1245 struct face *f2 = v2;
1246 int r;
1247
1248 r = f2->score - f1->score;
1249 if (r) {
1250 return r;
1251 }
1252
1253 if (f1->random < f2->random)
1254 return -1;
1255 else if (f1->random > f2->random)
1256 return 1;
1257
1258 /*
1259 * It's _just_ possible that two faces might have been given
1260 * the same random value. In that situation, fall back to
1261 * comparing based on the positions within the grid's face-list.
1262 * This introduces a tiny directional bias, but not a significant one.
1263 */
1264 return get_face_cmpfn(f1, f2);
1265 }
1266
1267 enum { FACE_LIT, FACE_UNLIT };
1268
1269 /* face should be of type grid_face* here. */
1270 #define FACE_LIT_STATE(face) \
1271 ( (face) == NULL ? FACE_UNLIT : \
1272 board[(face) - g->faces] )
1273
1274 /* 'board' is an array of these enums, indicating which faces are
1275 * currently lit. Returns whether it's legal to light up the
1276 * given face. */
1277 static int can_light_face(grid *g, char* board, int face_index)
1278 {
1279 int i, j;
1280 grid_face *test_face = g->faces + face_index;
1281 grid_face *starting_face, *current_face;
1282 int transitions;
1283 int current_state, s;
1284 int found_lit_neighbour = FALSE;
1285 assert(board[face_index] == FACE_UNLIT);
1286
1287 /* Can only consider a face for lighting if it's adjacent to an
1288 * already lit face. */
1289 for (i = 0; i < test_face->order; i++) {
1290 grid_edge *e = test_face->edges[i];
1291 grid_face *f = (e->face1 == test_face) ? e->face2 : e->face1;
1292 if (FACE_LIT_STATE(f) == FACE_LIT) {
1293 found_lit_neighbour = TRUE;
1294 break;
1295 }
1296 }
1297 if (!found_lit_neighbour)
1298 return FALSE;
1299
1300 /* Need to avoid creating a loop of lit faces around some unlit faces.
1301 * Also need to avoid meeting another lit face at a corner, with
1302 * unlit faces in between. Here's a simple test that (I believe) takes
1303 * care of both these conditions:
1304 *
1305 * Take the circular path formed by this face's edges, and inflate it
1306 * slightly outwards. Imagine walking around this path and consider
1307 * the faces that you visit in sequence. This will include all faces
1308 * touching the given face, either along an edge or just at a corner.
1309 * Count the number of LIT/UNLIT transitions you encounter, as you walk
1310 * along the complete loop. This will obviously turn out to be an even
1311 * number.
1312 * If 0, we're either in a completely unlit zone, or this face is a hole
1313 * in a completely lit zone. If the former, we would create a brand new
1314 * island by lighting this face. And the latter ought to be impossible -
1315 * it would mean there's already a lit loop, so something went wrong
1316 * earlier.
1317 * If 4 or greater, there are too many separate lit regions touching this
1318 * face, and lighting it up would create a loop or a corner-violation.
1319 * The only allowed case is when the count is exactly 2. */
1320
1321 /* i points to a dot around the test face.
1322 * j points to a face around the i^th dot.
1323 * The current face will always be:
1324 * test_face->dots[i]->faces[j]
1325 * We assume dots go clockwise around the test face,
1326 * and faces go clockwise around dots. */
1327 i = j = 0;
1328 starting_face = test_face->dots[0]->faces[0];
1329 if (starting_face == test_face) {
1330 j = 1;
1331 starting_face = test_face->dots[0]->faces[1];
1332 }
1333 current_face = starting_face;
1334 transitions = 0;
1335 current_state = FACE_LIT_STATE(current_face);
1336
1337 do {
1338 /* Advance to next face.
1339 * Need to loop here because it might take several goes to
1340 * find it. */
1341 while (TRUE) {
1342 j++;
1343 if (j == test_face->dots[i]->order)
1344 j = 0;
1345
1346 if (test_face->dots[i]->faces[j] == test_face) {
1347 /* Advance to next dot round test_face, then
1348 * find current_face around new dot
1349 * and advance to the next face clockwise */
1350 i++;
1351 if (i == test_face->order)
1352 i = 0;
1353 for (j = 0; j < test_face->dots[i]->order; j++) {
1354 if (test_face->dots[i]->faces[j] == current_face)
1355 break;
1356 }
1357 /* Must actually find current_face around new dot,
1358 * or else something's wrong with the grid. */
1359 assert(j != test_face->dots[i]->order);
1360 /* Found, so advance to next face and try again */
1361 } else {
1362 break;
1363 }
1364 }
1365 /* (i,j) are now advanced to next face */
1366 current_face = test_face->dots[i]->faces[j];
1367 s = FACE_LIT_STATE(current_face);
1368 if (s != current_state) {
1369 ++transitions;
1370 current_state = s;
1371 if (transitions > 2)
1372 return FALSE; /* no point in continuing */
1373 }
1374 } while (current_face != starting_face);
1375
1376 return (transitions == 2) ? TRUE : FALSE;
1377 }
1378
1379 /* The 'score' of a face reflects its current desirability for selection
1380 * as the next face to light. We want to encourage moving into uncharted
1381 * areas so we give scores according to how many of the face's neighbours
1382 * are currently unlit. */
1383 static int face_score(grid *g, char *board, grid_face *face)
1384 {
1385 /* Simple formula: score = neighbours unlit - neighbours lit */
1386 int lit_count = 0, unlit_count = 0;
1387 int i;
1388 grid_face *f;
1389 grid_edge *e;
1390 for (i = 0; i < face->order; i++) {
1391 e = face->edges[i];
1392 f = (e->face1 == face) ? e->face2 : e->face1;
1393 if (FACE_LIT_STATE(f) == FACE_LIT)
1394 ++lit_count;
1395 else
1396 ++unlit_count;
1397 }
1398 return unlit_count - lit_count;
1399 }
1400
1401 /* Generate a new complete set of clues for the given game_state. */
1402 static void add_full_clues(game_state *state, random_state *rs)
1403 {
1404 signed char *clues = state->clues;
1405 char *board;
1406 grid *g = state->game_grid;
1407 int i, j, c;
1408 int num_faces = g->num_faces;
1409 int first_time = TRUE;
1410
1411 struct face *face, *tmpface;
1412 struct face face_pos;
1413
1414 /* These will contain exactly the same information, sorted into different
1415 * orders */
1416 tree234 *lightable_faces_sorted, *lightable_faces_gettable;
1417
1418 #define IS_LIGHTING_CANDIDATE(i) \
1419 (board[i] == FACE_UNLIT && \
1420 can_light_face(g, board, i))
1421
1422 board = snewn(num_faces, char);
1423
1424 /* Make a board */
1425 memset(board, FACE_UNLIT, num_faces);
1426
1427 /* We need a way of favouring faces that will increase our loopiness.
1428 * We do this by maintaining a list of all candidate faces sorted by
1429 * their score and choose randomly from that with appropriate skew.
1430 * In order to avoid consistently biasing towards particular faces, we
1431 * need the sort order _within_ each group of scores to be completely
1432 * random. But it would be abusing the hospitality of the tree234 data
1433 * structure if our comparison function were nondeterministic :-). So with
1434 * each face we associate a random number that does not change during a
1435 * particular run of the generator, and use that as a secondary sort key.
1436 * Yes, this means we will be biased towards particular random faces in
1437 * any one run but that doesn't actually matter. */
1438
1439 lightable_faces_sorted = newtree234(face_sort_cmpfn);
1440 lightable_faces_gettable = newtree234(get_face_cmpfn);
1441 #define ADD_FACE(f) \
1442 do { \
1443 struct face *x = add234(lightable_faces_sorted, f); \
1444 assert(x == f); \
1445 x = add234(lightable_faces_gettable, f); \
1446 assert(x == f); \
1447 } while (0)
1448
1449 #define REMOVE_FACE(f) \
1450 do { \
1451 struct face *x = del234(lightable_faces_sorted, f); \
1452 assert(x); \
1453 x = del234(lightable_faces_gettable, f); \
1454 assert(x); \
1455 } while (0)
1456
1457 /* Light faces one at a time until the board is interesting enough */
1458 while (TRUE)
1459 {
1460 if (first_time) {
1461 first_time = FALSE;
1462 /* lightable_faces_xxx are empty, so start the process by
1463 * lighting up the middle face. These tree234s should
1464 * remain empty, consistent with what would happen if
1465 * first_time were FALSE. */
1466 board[g->middle_face - g->faces] = FACE_LIT;
1467 face = snew(struct face);
1468 face->f = g->middle_face;
1469 /* No need to initialise any more of 'face' here, no other fields
1470 * are used in this case. */
1471 } else {
1472 /* We have count234(lightable_faces_gettable) possibilities, and in
1473 * lightable_faces_sorted they are sorted with the most desirable
1474 * first. */
1475 c = count234(lightable_faces_sorted);
1476 if (c == 0)
1477 break;
1478 assert(c == count234(lightable_faces_gettable));
1479
1480 /* Check that the best face available is any good */
1481 face = (struct face *)index234(lightable_faces_sorted, 0);
1482 assert(face);
1483
1484 /*
1485 * The situation for a general grid is slightly different from
1486 * a square grid. Decreasing the perimeter should be allowed
1487 * sometimes (think about creating a hexagon of lit triangles,
1488 * for example). For if it were _never_ done, then the user would
1489 * be able to illicitly deduce certain things. So we do it
1490 * sometimes but not always.
1491 */
1492 if (face->score <= 0 && random_upto(rs, 2) == 0) {
1493 break;
1494 }
1495
1496 assert(face->f); /* not the infinite face */
1497 assert(FACE_LIT_STATE(face->f) == FACE_UNLIT);
1498
1499 /* Update data structures */
1500 /* Light up the face and remove it from the lists */
1501 board[face->f - g->faces] = FACE_LIT;
1502 REMOVE_FACE(face);
1503 }
1504
1505 /* The face we've just lit up potentially affects the lightability
1506 * of any neighbouring faces (touching at a corner or edge). So the
1507 * search needs to be conducted around all faces touching the one
1508 * we've just lit. Iterate over its corners, then over each corner's
1509 * faces. */
1510 for (i = 0; i < face->f->order; i++) {
1511 grid_dot *d = face->f->dots[i];
1512 for (j = 0; j < d->order; j++) {
1513 grid_face *f2 = d->faces[j];
1514 if (f2 == NULL)
1515 continue;
1516 if (f2 == face->f)
1517 continue;
1518 face_pos.f = f2;
1519 tmpface = find234(lightable_faces_gettable, &face_pos, NULL);
1520 if (tmpface) {
1521 assert(tmpface->f == face_pos.f);
1522 assert(FACE_LIT_STATE(tmpface->f) == FACE_UNLIT);
1523 REMOVE_FACE(tmpface);
1524 } else {
1525 tmpface = snew(struct face);
1526 tmpface->f = face_pos.f;
1527 tmpface->random = random_bits(rs, 31);
1528 }
1529 tmpface->score = face_score(g, board, tmpface->f);
1530
1531 if (IS_LIGHTING_CANDIDATE(tmpface->f - g->faces)) {
1532 ADD_FACE(tmpface);
1533 } else {
1534 sfree(tmpface);
1535 }
1536 }
1537 }
1538 sfree(face);
1539 }
1540
1541 /* Clean up */
1542 while ((face = delpos234(lightable_faces_gettable, 0)) != NULL)
1543 sfree(face);
1544 freetree234(lightable_faces_gettable);
1545 freetree234(lightable_faces_sorted);
1546
1547 /* Fill out all the clues by initialising to 0, then iterating over
1548 * all edges and incrementing each clue as we find edges that border
1549 * between LIT/UNLIT faces */
1550 memset(clues, 0, num_faces);
1551 for (i = 0; i < g->num_edges; i++) {
1552 grid_edge *e = g->edges + i;
1553 grid_face *f1 = e->face1;
1554 grid_face *f2 = e->face2;
1555 if (FACE_LIT_STATE(f1) != FACE_LIT_STATE(f2)) {
1556 if (f1) clues[f1 - g->faces]++;
1557 if (f2) clues[f2 - g->faces]++;
1558 }
1559 }
1560
1561 sfree(board);
1562 }
1563
1564
1565 static int game_has_unique_soln(const game_state *state, int diff)
1566 {
1567 int ret;
1568 solver_state *sstate_new;
1569 solver_state *sstate = new_solver_state((game_state *)state, diff);
1570
1571 sstate_new = solve_game_rec(sstate, diff);
1572
1573 assert(sstate_new->solver_status != SOLVER_MISTAKE);
1574 ret = (sstate_new->solver_status == SOLVER_SOLVED);
1575
1576 free_solver_state(sstate_new);
1577 free_solver_state(sstate);
1578
1579 return ret;
1580 }
1581
1582
1583 /* Remove clues one at a time at random. */
1584 static game_state *remove_clues(game_state *state, random_state *rs,
1585 int diff)
1586 {
1587 int *face_list;
1588 int num_faces = state->game_grid->num_faces;
1589 game_state *ret = dup_game(state), *saved_ret;
1590 int n;
1591
1592 /* We need to remove some clues. We'll do this by forming a list of all
1593 * available clues, shuffling it, then going along one at a
1594 * time clearing each clue in turn for which doing so doesn't render the
1595 * board unsolvable. */
1596 face_list = snewn(num_faces, int);
1597 for (n = 0; n < num_faces; ++n) {
1598 face_list[n] = n;
1599 }
1600
1601 shuffle(face_list, num_faces, sizeof(int), rs);
1602
1603 for (n = 0; n < num_faces; ++n) {
1604 saved_ret = dup_game(ret);
1605 ret->clues[face_list[n]] = -1;
1606
1607 if (game_has_unique_soln(ret, diff)) {
1608 free_game(saved_ret);
1609 } else {
1610 free_game(ret);
1611 ret = saved_ret;
1612 }
1613 }
1614 sfree(face_list);
1615
1616 return ret;
1617 }
1618
1619
1620 static char *new_game_desc(game_params *params, random_state *rs,
1621 char **aux, int interactive)
1622 {
1623 /* solution and description both use run-length encoding in obvious ways */
1624 char *retval;
1625 grid *g;
1626 game_state *state = snew(game_state);
1627 game_state *state_new;
1628 params_generate_grid(params);
1629 state->game_grid = g = params->game_grid;
1630 g->refcount++;
1631 state->clues = snewn(g->num_faces, signed char);
1632 state->lines = snewn(g->num_edges, char);
1633 state->line_errors = snewn(g->num_edges, unsigned char);
1634
1635 state->grid_type = params->type;
1636
1637 newboard_please:
1638
1639 memset(state->lines, LINE_UNKNOWN, g->num_edges);
1640 memset(state->line_errors, 0, g->num_edges);
1641
1642 state->solved = state->cheated = FALSE;
1643
1644 /* Get a new random solvable board with all its clues filled in. Yes, this
1645 * can loop for ever if the params are suitably unfavourable, but
1646 * preventing games smaller than 4x4 seems to stop this happening */
1647 do {
1648 add_full_clues(state, rs);
1649 } while (!game_has_unique_soln(state, params->diff));
1650
1651 state_new = remove_clues(state, rs, params->diff);
1652 free_game(state);
1653 state = state_new;
1654
1655
1656 if (params->diff > 0 && game_has_unique_soln(state, params->diff-1)) {
1657 #ifdef SHOW_WORKING
1658 fprintf(stderr, "Rejecting board, it is too easy\n");
1659 #endif
1660 goto newboard_please;
1661 }
1662
1663 retval = state_to_text(state);
1664
1665 free_game(state);
1666
1667 assert(!validate_desc(params, retval));
1668
1669 return retval;
1670 }
1671
1672 static game_state *new_game(midend *me, game_params *params, char *desc)
1673 {
1674 int i;
1675 game_state *state = snew(game_state);
1676 int empties_to_make = 0;
1677 int n;
1678 const char *dp = desc;
1679 grid *g;
1680 int num_faces, num_edges;
1681
1682 params_generate_grid(params);
1683 state->game_grid = g = params->game_grid;
1684 g->refcount++;
1685 num_faces = g->num_faces;
1686 num_edges = g->num_edges;
1687
1688 state->clues = snewn(num_faces, signed char);
1689 state->lines = snewn(num_edges, char);
1690 state->line_errors = snewn(num_edges, unsigned char);
1691
1692 state->solved = state->cheated = FALSE;
1693
1694 state->grid_type = params->type;
1695
1696 for (i = 0; i < num_faces; i++) {
1697 if (empties_to_make) {
1698 empties_to_make--;
1699 state->clues[i] = -1;
1700 continue;
1701 }
1702
1703 assert(*dp);
1704 n = *dp - '0';
1705 if (n >= 0 && n < 10) {
1706 state->clues[i] = n;
1707 } else {
1708 n = *dp - 'a' + 1;
1709 assert(n > 0);
1710 state->clues[i] = -1;
1711 empties_to_make = n - 1;
1712 }
1713 ++dp;
1714 }
1715
1716 memset(state->lines, LINE_UNKNOWN, num_edges);
1717 memset(state->line_errors, 0, num_edges);
1718 return state;
1719 }
1720
1721 /* Calculates the line_errors data, and checks if the current state is a
1722 * solution */
1723 static int check_completion(game_state *state)
1724 {
1725 grid *g = state->game_grid;
1726 int *dsf;
1727 int num_faces = g->num_faces;
1728 int i;
1729 int infinite_area, finite_area;
1730 int loops_found = 0;
1731 int found_edge_not_in_loop = FALSE;
1732
1733 memset(state->line_errors, 0, g->num_edges);
1734
1735 /* LL implementation of SGT's idea:
1736 * A loop will partition the grid into an inside and an outside.
1737 * If there is more than one loop, the grid will be partitioned into
1738 * even more distinct regions. We can therefore track equivalence of
1739 * faces, by saying that two faces are equivalent when there is a non-YES
1740 * edge between them.
1741 * We could keep track of the number of connected components, by counting
1742 * the number of dsf-merges that aren't no-ops.
1743 * But we're only interested in 3 separate cases:
1744 * no loops, one loop, more than one loop.
1745 *
1746 * No loops: all faces are equivalent to the infinite face.
1747 * One loop: only two equivalence classes - finite and infinite.
1748 * >= 2 loops: there are 2 distinct finite regions.
1749 *
1750 * So we simply make two passes through all the edges.
1751 * In the first pass, we dsf-merge the two faces bordering each non-YES
1752 * edge.
1753 * In the second pass, we look for YES-edges bordering:
1754 * a) two non-equivalent faces.
1755 * b) two non-equivalent faces, and one of them is part of a different
1756 * finite area from the first finite area we've seen.
1757 *
1758 * An occurrence of a) means there is at least one loop.
1759 * An occurrence of b) means there is more than one loop.
1760 * Edges satisfying a) are marked as errors.
1761 *
1762 * While we're at it, we set a flag if we find a YES edge that is not
1763 * part of a loop.
1764 * This information will help decide, if there's a single loop, whether it
1765 * is a candidate for being a solution (that is, all YES edges are part of
1766 * this loop).
1767 *
1768 * If there is a candidate loop, we then go through all clues and check
1769 * they are all satisfied. If so, we have found a solution and we can
1770 * unmark all line_errors.
1771 */
1772
1773 /* Infinite face is at the end - its index is num_faces.
1774 * This macro is just to make this obvious! */
1775 #define INF_FACE num_faces
1776 dsf = snewn(num_faces + 1, int);
1777 dsf_init(dsf, num_faces + 1);
1778
1779 /* First pass */
1780 for (i = 0; i < g->num_edges; i++) {
1781 grid_edge *e = g->edges + i;
1782 int f1 = e->face1 ? e->face1 - g->faces : INF_FACE;
1783 int f2 = e->face2 ? e->face2 - g->faces : INF_FACE;
1784 if (state->lines[i] != LINE_YES)
1785 dsf_merge(dsf, f1, f2);
1786 }
1787
1788 /* Second pass */
1789 infinite_area = dsf_canonify(dsf, INF_FACE);
1790 finite_area = -1;
1791 for (i = 0; i < g->num_edges; i++) {
1792 grid_edge *e = g->edges + i;
1793 int f1 = e->face1 ? e->face1 - g->faces : INF_FACE;
1794 int can1 = dsf_canonify(dsf, f1);
1795 int f2 = e->face2 ? e->face2 - g->faces : INF_FACE;
1796 int can2 = dsf_canonify(dsf, f2);
1797 if (state->lines[i] != LINE_YES) continue;
1798
1799 if (can1 == can2) {
1800 /* Faces are equivalent, so this edge not part of a loop */
1801 found_edge_not_in_loop = TRUE;
1802 continue;
1803 }
1804 state->line_errors[i] = TRUE;
1805 if (loops_found == 0) loops_found = 1;
1806
1807 /* Don't bother with further checks if we've already found 2 loops */
1808 if (loops_found == 2) continue;
1809
1810 if (finite_area == -1) {
1811 /* Found our first finite area */
1812 if (can1 != infinite_area)
1813 finite_area = can1;
1814 else
1815 finite_area = can2;
1816 }
1817
1818 /* Have we found a second area? */
1819 if (finite_area != -1) {
1820 if (can1 != infinite_area && can1 != finite_area) {
1821 loops_found = 2;
1822 continue;
1823 }
1824 if (can2 != infinite_area && can2 != finite_area) {
1825 loops_found = 2;
1826 }
1827 }
1828 }
1829
1830 /*
1831 printf("loops_found = %d\n", loops_found);
1832 printf("found_edge_not_in_loop = %s\n",
1833 found_edge_not_in_loop ? "TRUE" : "FALSE");
1834 */
1835
1836 sfree(dsf); /* No longer need the dsf */
1837
1838 /* Have we found a candidate loop? */
1839 if (loops_found == 1 && !found_edge_not_in_loop) {
1840 /* Yes, so check all clues are satisfied */
1841 int found_clue_violation = FALSE;
1842 for (i = 0; i < num_faces; i++) {
1843 int c = state->clues[i];
1844 if (c >= 0) {
1845 if (face_order(state, i, LINE_YES) != c) {
1846 found_clue_violation = TRUE;
1847 break;
1848 }
1849 }
1850 }
1851
1852 if (!found_clue_violation) {
1853 /* The loop is good */
1854 memset(state->line_errors, 0, g->num_edges);
1855 return TRUE; /* No need to bother checking for dot violations */
1856 }
1857 }
1858
1859 /* Check for dot violations */
1860 for (i = 0; i < g->num_dots; i++) {
1861 int yes = dot_order(state, i, LINE_YES);
1862 int unknown = dot_order(state, i, LINE_UNKNOWN);
1863 if ((yes == 1 && unknown == 0) || (yes >= 3)) {
1864 /* violation, so mark all YES edges as errors */
1865 grid_dot *d = g->dots + i;
1866 int j;
1867 for (j = 0; j < d->order; j++) {
1868 int e = d->edges[j] - g->edges;
1869 if (state->lines[e] == LINE_YES)
1870 state->line_errors[e] = TRUE;
1871 }
1872 }
1873 }
1874 return FALSE;
1875 }
1876
1877 /* ----------------------------------------------------------------------
1878 * Solver logic
1879 *
1880 * Our solver modes operate as follows. Each mode also uses the modes above it.
1881 *
1882 * Easy Mode
1883 * Just implement the rules of the game.
1884 *
1885 * Normal Mode
1886 * For each (adjacent) pair of lines through each dot we store a bit for
1887 * whether at least one of them is on and whether at most one is on. (If we
1888 * know both or neither is on that's already stored more directly.)
1889 *
1890 * Advanced Mode
1891 * Use edsf data structure to make equivalence classes of lines that are
1892 * known identical to or opposite to one another.
1893 */
1894
1895
1896 /* DLines:
1897 * For general grids, we consider "dlines" to be pairs of lines joined
1898 * at a dot. The lines must be adjacent around the dot, so we can think of
1899 * a dline as being a dot+face combination. Or, a dot+edge combination where
1900 * the second edge is taken to be the next clockwise edge from the dot.
1901 * Original loopy code didn't have this extra restriction of the lines being
1902 * adjacent. From my tests with square grids, this extra restriction seems to
1903 * take little, if anything, away from the quality of the puzzles.
1904 * A dline can be uniquely identified by an edge/dot combination, given that
1905 * a dline-pair always goes clockwise around its common dot. The edge/dot
1906 * combination can be represented by an edge/bool combination - if bool is
1907 * TRUE, use edge->dot1 else use edge->dot2. So the total number of dlines is
1908 * exactly twice the number of edges in the grid - although the dlines
1909 * spanning the infinite face are not all that useful to the solver.
1910 * Note that, by convention, a dline goes clockwise around its common dot,
1911 * which means the dline goes anti-clockwise around its common face.
1912 */
1913
1914 /* Helper functions for obtaining an index into an array of dlines, given
1915 * various information. We assume the grid layout conventions about how
1916 * the various lists are interleaved - see grid_make_consistent() for
1917 * details. */
1918
1919 /* i points to the first edge of the dline pair, reading clockwise around
1920 * the dot. */
1921 static int dline_index_from_dot(grid *g, grid_dot *d, int i)
1922 {
1923 grid_edge *e = d->edges[i];
1924 int ret;
1925 #ifdef DEBUG_DLINES
1926 grid_edge *e2;
1927 int i2 = i+1;
1928 if (i2 == d->order) i2 = 0;
1929 e2 = d->edges[i2];
1930 #endif
1931 ret = 2 * (e - g->edges) + ((e->dot1 == d) ? 1 : 0);
1932 #ifdef DEBUG_DLINES
1933 printf("dline_index_from_dot: d=%d,i=%d, edges [%d,%d] - %d\n",
1934 (int)(d - g->dots), i, (int)(e - g->edges),
1935 (int)(e2 - g->edges), ret);
1936 #endif
1937 return ret;
1938 }
1939 /* i points to the second edge of the dline pair, reading clockwise around
1940 * the face. That is, the edges of the dline, starting at edge{i}, read
1941 * anti-clockwise around the face. By layout conventions, the common dot
1942 * of the dline will be f->dots[i] */
1943 static int dline_index_from_face(grid *g, grid_face *f, int i)
1944 {
1945 grid_edge *e = f->edges[i];
1946 grid_dot *d = f->dots[i];
1947 int ret;
1948 #ifdef DEBUG_DLINES
1949 grid_edge *e2;
1950 int i2 = i - 1;
1951 if (i2 < 0) i2 += f->order;
1952 e2 = f->edges[i2];
1953 #endif
1954 ret = 2 * (e - g->edges) + ((e->dot1 == d) ? 1 : 0);
1955 #ifdef DEBUG_DLINES
1956 printf("dline_index_from_face: f=%d,i=%d, edges [%d,%d] - %d\n",
1957 (int)(f - g->faces), i, (int)(e - g->edges),
1958 (int)(e2 - g->edges), ret);
1959 #endif
1960 return ret;
1961 }
1962 static int is_atleastone(const char *dline_array, int index)
1963 {
1964 return BIT_SET(dline_array[index], 0);
1965 }
1966 static int set_atleastone(char *dline_array, int index)
1967 {
1968 return SET_BIT(dline_array[index], 0);
1969 }
1970 static int is_atmostone(const char *dline_array, int index)
1971 {
1972 return BIT_SET(dline_array[index], 1);
1973 }
1974 static int set_atmostone(char *dline_array, int index)
1975 {
1976 return SET_BIT(dline_array[index], 1);
1977 }
1978
1979 static void array_setall(char *array, char from, char to, int len)
1980 {
1981 char *p = array, *p_old = p;
1982 int len_remaining = len;
1983
1984 while ((p = memchr(p, from, len_remaining))) {
1985 *p = to;
1986 len_remaining -= p - p_old;
1987 p_old = p;
1988 }
1989 }
1990
1991 /* Helper, called when doing dline dot deductions, in the case where we
1992 * have 4 UNKNOWNs, and two of them (adjacent) have *exactly* one YES between
1993 * them (because of dline atmostone/atleastone).
1994 * On entry, edge points to the first of these two UNKNOWNs. This function
1995 * will find the opposite UNKNOWNS (if they are adjacent to one another)
1996 * and set their corresponding dline to atleastone. (Setting atmostone
1997 * already happens in earlier dline deductions) */
1998 static int dline_set_opp_atleastone(solver_state *sstate,
1999 grid_dot *d, int edge)
2000 {
2001 game_state *state = sstate->state;
2002 grid *g = state->game_grid;
2003 int N = d->order;
2004 int opp, opp2;
2005 for (opp = 0; opp < N; opp++) {
2006 int opp_dline_index;
2007 if (opp == edge || opp == edge+1 || opp == edge-1)
2008 continue;
2009 if (opp == 0 && edge == N-1)
2010 continue;
2011 if (opp == N-1 && edge == 0)
2012 continue;
2013 opp2 = opp + 1;
2014 if (opp2 == N) opp2 = 0;
2015 /* Check if opp, opp2 point to LINE_UNKNOWNs */
2016 if (state->lines[d->edges[opp] - g->edges] != LINE_UNKNOWN)
2017 continue;
2018 if (state->lines[d->edges[opp2] - g->edges] != LINE_UNKNOWN)
2019 continue;
2020 /* Found opposite UNKNOWNS and they're next to each other */
2021 opp_dline_index = dline_index_from_dot(g, d, opp);
2022 return set_atleastone(sstate->normal->dlines, opp_dline_index);
2023 }
2024 return FALSE;
2025 }
2026
2027
2028 /* Set pairs of lines around this face which are known to be identical, to
2029 * the given line_state */
2030 static int face_setall_identical(solver_state *sstate, int face_index,
2031 enum line_state line_new)
2032 {
2033 /* can[dir] contains the canonical line associated with the line in
2034 * direction dir from the square in question. Similarly inv[dir] is
2035 * whether or not the line in question is inverse to its canonical
2036 * element. */
2037 int retval = FALSE;
2038 game_state *state = sstate->state;
2039 grid *g = state->game_grid;
2040 grid_face *f = g->faces + face_index;
2041 int N = f->order;
2042 int i, j;
2043 int can1, can2, inv1, inv2;
2044
2045 for (i = 0; i < N; i++) {
2046 int line1_index = f->edges[i] - g->edges;
2047 if (state->lines[line1_index] != LINE_UNKNOWN)
2048 continue;
2049 for (j = i + 1; j < N; j++) {
2050 int line2_index = f->edges[j] - g->edges;
2051 if (state->lines[line2_index] != LINE_UNKNOWN)
2052 continue;
2053
2054 /* Found two UNKNOWNS */
2055 can1 = edsf_canonify(sstate->hard->linedsf, line1_index, &inv1);
2056 can2 = edsf_canonify(sstate->hard->linedsf, line2_index, &inv2);
2057 if (can1 == can2 && inv1 == inv2) {
2058 solver_set_line(sstate, line1_index, line_new);
2059 solver_set_line(sstate, line2_index, line_new);
2060 }
2061 }
2062 }
2063 return retval;
2064 }
2065
2066 /* Given a dot or face, and a count of LINE_UNKNOWNs, find them and
2067 * return the edge indices into e. */
2068 static void find_unknowns(game_state *state,
2069 grid_edge **edge_list, /* Edge list to search (from a face or a dot) */
2070 int expected_count, /* Number of UNKNOWNs (comes from solver's cache) */
2071 int *e /* Returned edge indices */)
2072 {
2073 int c = 0;
2074 grid *g = state->game_grid;
2075 while (c < expected_count) {
2076 int line_index = *edge_list - g->edges;
2077 if (state->lines[line_index] == LINE_UNKNOWN) {
2078 e[c] = line_index;
2079 c++;
2080 }
2081 ++edge_list;
2082 }
2083 }
2084
2085 /* If we have a list of edges, and we know whether the number of YESs should
2086 * be odd or even, and there are only a few UNKNOWNs, we can do some simple
2087 * linedsf deductions. This can be used for both face and dot deductions.
2088 * Returns the difficulty level of the next solver that should be used,
2089 * or DIFF_MAX if no progress was made. */
2090 static int parity_deductions(solver_state *sstate,
2091 grid_edge **edge_list, /* Edge list (from a face or a dot) */
2092 int total_parity, /* Expected number of YESs modulo 2 (either 0 or 1) */
2093 int unknown_count)
2094 {
2095 game_state *state = sstate->state;
2096 int diff = DIFF_MAX;
2097 int *linedsf = sstate->hard->linedsf;
2098
2099 if (unknown_count == 2) {
2100 /* Lines are known alike/opposite, depending on inv. */
2101 int e[2];
2102 find_unknowns(state, edge_list, 2, e);
2103 if (merge_lines(sstate, e[0], e[1], total_parity))
2104 diff = min(diff, DIFF_HARD);
2105 } else if (unknown_count == 3) {
2106 int e[3];
2107 int can[3]; /* canonical edges */
2108 int inv[3]; /* whether can[x] is inverse to e[x] */
2109 find_unknowns(state, edge_list, 3, e);
2110 can[0] = edsf_canonify(linedsf, e[0], inv);
2111 can[1] = edsf_canonify(linedsf, e[1], inv+1);
2112 can[2] = edsf_canonify(linedsf, e[2], inv+2);
2113 if (can[0] == can[1]) {
2114 if (solver_set_line(sstate, e[2], (total_parity^inv[0]^inv[1]) ?
2115 LINE_YES : LINE_NO))
2116 diff = min(diff, DIFF_EASY);
2117 }
2118 if (can[0] == can[2]) {
2119 if (solver_set_line(sstate, e[1], (total_parity^inv[0]^inv[2]) ?
2120 LINE_YES : LINE_NO))
2121 diff = min(diff, DIFF_EASY);
2122 }
2123 if (can[1] == can[2]) {
2124 if (solver_set_line(sstate, e[0], (total_parity^inv[1]^inv[2]) ?
2125 LINE_YES : LINE_NO))
2126 diff = min(diff, DIFF_EASY);
2127 }
2128 } else if (unknown_count == 4) {
2129 int e[4];
2130 int can[4]; /* canonical edges */
2131 int inv[4]; /* whether can[x] is inverse to e[x] */
2132 find_unknowns(state, edge_list, 4, e);
2133 can[0] = edsf_canonify(linedsf, e[0], inv);
2134 can[1] = edsf_canonify(linedsf, e[1], inv+1);
2135 can[2] = edsf_canonify(linedsf, e[2], inv+2);
2136 can[3] = edsf_canonify(linedsf, e[3], inv+3);
2137 if (can[0] == can[1]) {
2138 if (merge_lines(sstate, e[2], e[3], total_parity^inv[0]^inv[1]))
2139 diff = min(diff, DIFF_HARD);
2140 } else if (can[0] == can[2]) {
2141 if (merge_lines(sstate, e[1], e[3], total_parity^inv[0]^inv[2]))
2142 diff = min(diff, DIFF_HARD);
2143 } else if (can[0] == can[3]) {
2144 if (merge_lines(sstate, e[1], e[2], total_parity^inv[0]^inv[3]))
2145 diff = min(diff, DIFF_HARD);
2146 } else if (can[1] == can[2]) {
2147 if (merge_lines(sstate, e[0], e[3], total_parity^inv[1]^inv[2]))
2148 diff = min(diff, DIFF_HARD);
2149 } else if (can[1] == can[3]) {
2150 if (merge_lines(sstate, e[0], e[2], total_parity^inv[1]^inv[3]))
2151 diff = min(diff, DIFF_HARD);
2152 } else if (can[2] == can[3]) {
2153 if (merge_lines(sstate, e[0], e[1], total_parity^inv[2]^inv[3]))
2154 diff = min(diff, DIFF_HARD);
2155 }
2156 }
2157 return diff;
2158 }
2159
2160
2161 /*
2162 * These are the main solver functions.
2163 *
2164 * Their return values are diff values corresponding to the lowest mode solver
2165 * that would notice the work that they have done. For example if the normal
2166 * mode solver adds actual lines or crosses, it will return DIFF_EASY as the
2167 * easy mode solver might be able to make progress using that. It doesn't make
2168 * sense for one of them to return a diff value higher than that of the
2169 * function itself.
2170 *
2171 * Each function returns the lowest value it can, as early as possible, in
2172 * order to try and pass as much work as possible back to the lower level
2173 * solvers which progress more quickly.
2174 */
2175
2176 /* PROPOSED NEW DESIGN:
2177 * We have a work queue consisting of 'events' notifying us that something has
2178 * happened that a particular solver mode might be interested in. For example
2179 * the hard mode solver might do something that helps the normal mode solver at
2180 * dot [x,y] in which case it will enqueue an event recording this fact. Then
2181 * we pull events off the work queue, and hand each in turn to the solver that
2182 * is interested in them. If a solver reports that it failed we pass the same
2183 * event on to progressively more advanced solvers and the loop detector. Once
2184 * we've exhausted an event, or it has helped us progress, we drop it and
2185 * continue to the next one. The events are sorted first in order of solver
2186 * complexity (easy first) then order of insertion (oldest first).
2187 * Once we run out of events we loop over each permitted solver in turn
2188 * (easiest first) until either a deduction is made (and an event therefore
2189 * emerges) or no further deductions can be made (in which case we've failed).
2190 *
2191 * QUESTIONS:
2192 * * How do we 'loop over' a solver when both dots and squares are concerned.
2193 * Answer: first all squares then all dots.
2194 */
2195
2196 static int easy_mode_deductions(solver_state *sstate)
2197 {
2198 int i, current_yes, current_no;
2199 game_state *state = sstate->state;
2200 grid *g = state->game_grid;
2201 int diff = DIFF_MAX;
2202
2203 /* Per-face deductions */
2204 for (i = 0; i < g->num_faces; i++) {
2205 grid_face *f = g->faces + i;
2206
2207 if (sstate->face_solved[i])
2208 continue;
2209
2210 current_yes = sstate->face_yes_count[i];
2211 current_no = sstate->face_no_count[i];
2212
2213 if (current_yes + current_no == f->order) {
2214 sstate->face_solved[i] = TRUE;
2215 continue;
2216 }
2217
2218 if (state->clues[i] < 0)
2219 continue;
2220
2221 if (state->clues[i] < current_yes) {
2222 sstate->solver_status = SOLVER_MISTAKE;
2223 return DIFF_EASY;
2224 }
2225 if (state->clues[i] == current_yes) {
2226 if (face_setall(sstate, i, LINE_UNKNOWN, LINE_NO))
2227 diff = min(diff, DIFF_EASY);
2228 sstate->face_solved[i] = TRUE;
2229 continue;
2230 }
2231
2232 if (f->order - state->clues[i] < current_no) {
2233 sstate->solver_status = SOLVER_MISTAKE;
2234 return DIFF_EASY;
2235 }
2236 if (f->order - state->clues[i] == current_no) {
2237 if (face_setall(sstate, i, LINE_UNKNOWN, LINE_YES))
2238 diff = min(diff, DIFF_EASY);
2239 sstate->face_solved[i] = TRUE;
2240 continue;
2241 }
2242 }
2243
2244 check_caches(sstate);
2245
2246 /* Per-dot deductions */
2247 for (i = 0; i < g->num_dots; i++) {
2248 grid_dot *d = g->dots + i;
2249 int yes, no, unknown;
2250
2251 if (sstate->dot_solved[i])
2252 continue;
2253
2254 yes = sstate->dot_yes_count[i];
2255 no = sstate->dot_no_count[i];
2256 unknown = d->order - yes - no;
2257
2258 if (yes == 0) {
2259 if (unknown == 0) {
2260 sstate->dot_solved[i] = TRUE;
2261 } else if (unknown == 1) {
2262 dot_setall(sstate, i, LINE_UNKNOWN, LINE_NO);
2263 diff = min(diff, DIFF_EASY);
2264 sstate->dot_solved[i] = TRUE;
2265 }
2266 } else if (yes == 1) {
2267 if (unknown == 0) {
2268 sstate->solver_status = SOLVER_MISTAKE;
2269 return DIFF_EASY;
2270 } else if (unknown == 1) {
2271 dot_setall(sstate, i, LINE_UNKNOWN, LINE_YES);
2272 diff = min(diff, DIFF_EASY);
2273 }
2274 } else if (yes == 2) {
2275 if (unknown > 0) {
2276 dot_setall(sstate, i, LINE_UNKNOWN, LINE_NO);
2277 diff = min(diff, DIFF_EASY);
2278 }
2279 sstate->dot_solved[i] = TRUE;
2280 } else {
2281 sstate->solver_status = SOLVER_MISTAKE;
2282 return DIFF_EASY;
2283 }
2284 }
2285
2286 check_caches(sstate);
2287
2288 return diff;
2289 }
2290
2291 static int normal_mode_deductions(solver_state *sstate)
2292 {
2293 game_state *state = sstate->state;
2294 grid *g = state->game_grid;
2295 char *dlines = sstate->normal->dlines;
2296 int i;
2297 int diff = DIFF_MAX;
2298
2299 /* ------ Face deductions ------ */
2300
2301 /* Given a set of dline atmostone/atleastone constraints, need to figure
2302 * out if we can deduce any further info. For more general faces than
2303 * squares, this turns out to be a tricky problem.
2304 * The approach taken here is to define (per face) NxN matrices:
2305 * "maxs" and "mins".
2306 * The entries maxs(j,k) and mins(j,k) define the upper and lower limits
2307 * for the possible number of edges that are YES between positions j and k
2308 * going clockwise around the face. Can think of j and k as marking dots
2309 * around the face (recall the labelling scheme: edge0 joins dot0 to dot1,
2310 * edge1 joins dot1 to dot2 etc).
2311 * Trivially, mins(j,j) = maxs(j,j) = 0, and we don't even bother storing
2312 * these. mins(j,j+1) and maxs(j,j+1) are determined by whether edge{j}
2313 * is YES, NO or UNKNOWN. mins(j,j+2) and maxs(j,j+2) are related to
2314 * the dline atmostone/atleastone status for edges j and j+1.
2315 *
2316 * Then we calculate the remaining entries recursively. We definitely
2317 * know that
2318 * mins(j,k) >= { mins(j,u) + mins(u,k) } for any u between j and k.
2319 * This is because any valid placement of YESs between j and k must give
2320 * a valid placement between j and u, and also between u and k.
2321 * I believe it's sufficient to use just the two values of u:
2322 * j+1 and j+2. Seems to work well in practice - the bounds we compute
2323 * are rigorous, even if they might not be best-possible.
2324 *
2325 * Once we have maxs and mins calculated, we can make inferences about
2326 * each dline{j,j+1} by looking at the possible complementary edge-counts
2327 * mins(j+2,j) and maxs(j+2,j) and comparing these with the face clue.
2328 * As well as dlines, we can make similar inferences about single edges.
2329 * For example, consider a pentagon with clue 3, and we know at most one
2330 * of (edge0, edge1) is YES, and at most one of (edge2, edge3) is YES.
2331 * We could then deduce edge4 is YES, because maxs(0,4) would be 2, so
2332 * that final edge would have to be YES to make the count up to 3.
2333 */
2334
2335 /* Much quicker to allocate arrays on the stack than the heap, so
2336 * define the largest possible face size, and base our array allocations
2337 * on that. We check this with an assertion, in case someone decides to
2338 * make a grid which has larger faces than this. Note, this algorithm
2339 * could get quite expensive if there are many large faces. */
2340 #define MAX_FACE_SIZE 8
2341
2342 for (i = 0; i < g->num_faces; i++) {
2343 int maxs[MAX_FACE_SIZE][MAX_FACE_SIZE];
2344 int mins[MAX_FACE_SIZE][MAX_FACE_SIZE];
2345 grid_face *f = g->faces + i;
2346 int N = f->order;
2347 int j,m;
2348 int clue = state->clues[i];
2349 assert(N <= MAX_FACE_SIZE);
2350 if (sstate->face_solved[i])
2351 continue;
2352 if (clue < 0) continue;
2353
2354 /* Calculate the (j,j+1) entries */
2355 for (j = 0; j < N; j++) {
2356 int edge_index = f->edges[j] - g->edges;
2357 int dline_index;
2358 enum line_state line1 = state->lines[edge_index];
2359 enum line_state line2;
2360 int tmp;
2361 int k = j + 1;
2362 if (k >= N) k = 0;
2363 maxs[j][k] = (line1 == LINE_NO) ? 0 : 1;
2364 mins[j][k] = (line1 == LINE_YES) ? 1 : 0;
2365 /* Calculate the (j,j+2) entries */
2366 dline_index = dline_index_from_face(g, f, k);
2367 edge_index = f->edges[k] - g->edges;
2368 line2 = state->lines[edge_index];
2369 k++;
2370 if (k >= N) k = 0;
2371
2372 /* max */
2373 tmp = 2;
2374 if (line1 == LINE_NO) tmp--;
2375 if (line2 == LINE_NO) tmp--;
2376 if (tmp == 2 && is_atmostone(dlines, dline_index))
2377 tmp = 1;
2378 maxs[j][k] = tmp;
2379
2380 /* min */
2381 tmp = 0;
2382 if (line1 == LINE_YES) tmp++;
2383 if (line2 == LINE_YES) tmp++;
2384 if (tmp == 0 && is_atleastone(dlines, dline_index))
2385 tmp = 1;
2386 mins[j][k] = tmp;
2387 }
2388
2389 /* Calculate the (j,j+m) entries for m between 3 and N-1 */
2390 for (m = 3; m < N; m++) {
2391 for (j = 0; j < N; j++) {
2392 int k = j + m;
2393 int u = j + 1;
2394 int v = j + 2;
2395 int tmp;
2396 if (k >= N) k -= N;
2397 if (u >= N) u -= N;
2398 if (v >= N) v -= N;
2399 maxs[j][k] = maxs[j][u] + maxs[u][k];
2400 mins[j][k] = mins[j][u] + mins[u][k];
2401 tmp = maxs[j][v] + maxs[v][k];
2402 maxs[j][k] = min(maxs[j][k], tmp);
2403 tmp = mins[j][v] + mins[v][k];
2404 mins[j][k] = max(mins[j][k], tmp);
2405 }
2406 }
2407
2408 /* See if we can make any deductions */
2409 for (j = 0; j < N; j++) {
2410 int k;
2411 grid_edge *e = f->edges[j];
2412 int line_index = e - g->edges;
2413 int dline_index;
2414
2415 if (state->lines[line_index] != LINE_UNKNOWN)
2416 continue;
2417 k = j + 1;
2418 if (k >= N) k = 0;
2419
2420 /* minimum YESs in the complement of this edge */
2421 if (mins[k][j] > clue) {
2422 sstate->solver_status = SOLVER_MISTAKE;
2423 return DIFF_EASY;
2424 }
2425 if (mins[k][j] == clue) {
2426 /* setting this edge to YES would make at least
2427 * (clue+1) edges - contradiction */
2428 solver_set_line(sstate, line_index, LINE_NO);
2429 diff = min(diff, DIFF_EASY);
2430 }
2431 if (maxs[k][j] < clue - 1) {
2432 sstate->solver_status = SOLVER_MISTAKE;
2433 return DIFF_EASY;
2434 }
2435 if (maxs[k][j] == clue - 1) {
2436 /* Only way to satisfy the clue is to set edge{j} as YES */
2437 solver_set_line(sstate, line_index, LINE_YES);
2438 diff = min(diff, DIFF_EASY);
2439 }
2440
2441 /* Now see if we can make dline deduction for edges{j,j+1} */
2442 e = f->edges[k];
2443 if (state->lines[e - g->edges] != LINE_UNKNOWN)
2444 /* Only worth doing this for an UNKNOWN,UNKNOWN pair.
2445 * Dlines where one of the edges is known, are handled in the
2446 * dot-deductions */
2447 continue;
2448
2449 dline_index = dline_index_from_face(g, f, k);
2450 k++;
2451 if (k >= N) k = 0;
2452
2453 /* minimum YESs in the complement of this dline */
2454 if (mins[k][j] > clue - 2) {
2455 /* Adding 2 YESs would break the clue */
2456 if (set_atmostone(dlines, dline_index))
2457 diff = min(diff, DIFF_NORMAL);
2458 }
2459 /* maximum YESs in the complement of this dline */
2460 if (maxs[k][j] < clue) {
2461 /* Adding 2 NOs would mean not enough YESs */
2462 if (set_atleastone(dlines, dline_index))
2463 diff = min(diff, DIFF_NORMAL);
2464 }
2465 }
2466 }
2467
2468 if (diff < DIFF_NORMAL)
2469 return diff;
2470
2471 /* ------ Dot deductions ------ */
2472
2473 for (i = 0; i < g->num_dots; i++) {
2474 grid_dot *d = g->dots + i;
2475 int N = d->order;
2476 int yes, no, unknown;
2477 int j;
2478 if (sstate->dot_solved[i])
2479 continue;
2480 yes = sstate->dot_yes_count[i];
2481 no = sstate->dot_no_count[i];
2482 unknown = N - yes - no;
2483
2484 for (j = 0; j < N; j++) {
2485 int k;
2486 int dline_index;
2487 int line1_index, line2_index;
2488 enum line_state line1, line2;
2489 k = j + 1;
2490 if (k >= N) k = 0;
2491 dline_index = dline_index_from_dot(g, d, j);
2492 line1_index = d->edges[j] - g->edges;
2493 line2_index = d->edges[k] - g->edges;
2494 line1 = state->lines[line1_index];
2495 line2 = state->lines[line2_index];
2496
2497 /* Infer dline state from line state */
2498 if (line1 == LINE_NO || line2 == LINE_NO) {
2499 if (set_atmostone(dlines, dline_index))
2500 diff = min(diff, DIFF_NORMAL);
2501 }
2502 if (line1 == LINE_YES || line2 == LINE_YES) {
2503 if (set_atleastone(dlines, dline_index))
2504 diff = min(diff, DIFF_NORMAL);
2505 }
2506 /* Infer line state from dline state */
2507 if (is_atmostone(dlines, dline_index)) {
2508 if (line1 == LINE_YES && line2 == LINE_UNKNOWN) {
2509 solver_set_line(sstate, line2_index, LINE_NO);
2510 diff = min(diff, DIFF_EASY);
2511 }
2512 if (line2 == LINE_YES && line1 == LINE_UNKNOWN) {
2513 solver_set_line(sstate, line1_index, LINE_NO);
2514 diff = min(diff, DIFF_EASY);
2515 }
2516 }
2517 if (is_atleastone(dlines, dline_index)) {
2518 if (line1 == LINE_NO && line2 == LINE_UNKNOWN) {
2519 solver_set_line(sstate, line2_index, LINE_YES);
2520 diff = min(diff, DIFF_EASY);
2521 }
2522 if (line2 == LINE_NO && line1 == LINE_UNKNOWN) {
2523 solver_set_line(sstate, line1_index, LINE_YES);
2524 diff = min(diff, DIFF_EASY);
2525 }
2526 }
2527 /* Deductions that depend on the numbers of lines.
2528 * Only bother if both lines are UNKNOWN, otherwise the
2529 * easy-mode solver (or deductions above) would have taken
2530 * care of it. */
2531 if (line1 != LINE_UNKNOWN || line2 != LINE_UNKNOWN)
2532 continue;
2533
2534 if (yes == 0 && unknown == 2) {
2535 /* Both these unknowns must be identical. If we know
2536 * atmostone or atleastone, we can make progress. */
2537 if (is_atmostone(dlines, dline_index)) {
2538 solver_set_line(sstate, line1_index, LINE_NO);
2539 solver_set_line(sstate, line2_index, LINE_NO);
2540 diff = min(diff, DIFF_EASY);
2541 }
2542 if (is_atleastone(dlines, dline_index)) {
2543 solver_set_line(sstate, line1_index, LINE_YES);
2544 solver_set_line(sstate, line2_index, LINE_YES);
2545 diff = min(diff, DIFF_EASY);
2546 }
2547 }
2548 if (yes == 1) {
2549 if (set_atmostone(dlines, dline_index))
2550 diff = min(diff, DIFF_NORMAL);
2551 if (unknown == 2) {
2552 if (set_atleastone(dlines, dline_index))
2553 diff = min(diff, DIFF_NORMAL);
2554 }
2555 }
2556
2557 /* If we have atleastone set for this dline, infer
2558 * atmostone for each "opposite" dline (that is, each
2559 * dline without edges in common with this one).
2560 * Again, this test is only worth doing if both these
2561 * lines are UNKNOWN. For if one of these lines were YES,
2562 * the (yes == 1) test above would kick in instead. */
2563 if (is_atleastone(dlines, dline_index)) {
2564 int opp;
2565 for (opp = 0; opp < N; opp++) {
2566 int opp_dline_index;
2567 if (opp == j || opp == j+1 || opp == j-1)
2568 continue;
2569 if (j == 0 && opp == N-1)
2570 continue;
2571 if (j == N-1 && opp == 0)
2572 continue;
2573 opp_dline_index = dline_index_from_dot(g, d, opp);
2574 if (set_atmostone(dlines, opp_dline_index))
2575 diff = min(diff, DIFF_NORMAL);
2576 }
2577
2578 if (yes == 0 && is_atmostone(dlines, dline_index)) {
2579 /* This dline has *exactly* one YES and there are no
2580 * other YESs. This allows more deductions. */
2581 if (unknown == 3) {
2582 /* Third unknown must be YES */
2583 for (opp = 0; opp < N; opp++) {
2584 int opp_index;
2585 if (opp == j || opp == k)
2586 continue;
2587 opp_index = d->edges[opp] - g->edges;
2588 if (state->lines[opp_index] == LINE_UNKNOWN) {
2589 solver_set_line(sstate, opp_index, LINE_YES);
2590 diff = min(diff, DIFF_EASY);
2591 }
2592 }
2593 } else if (unknown == 4) {
2594 /* Exactly one of opposite UNKNOWNS is YES. We've
2595 * already set atmostone, so set atleastone as well.
2596 */
2597 if (dline_set_opp_atleastone(sstate, d, j))
2598 diff = min(diff, DIFF_NORMAL);
2599 }
2600 }
2601 }
2602 }
2603 }
2604 return diff;
2605 }
2606
2607 static int hard_mode_deductions(solver_state *sstate)
2608 {
2609 game_state *state = sstate->state;
2610 grid *g = state->game_grid;
2611 char *dlines = sstate->normal->dlines;
2612 int i;
2613 int diff = DIFF_MAX;
2614 int diff_tmp;
2615
2616 /* ------ Face deductions ------ */
2617
2618 /* A fully-general linedsf deduction seems overly complicated
2619 * (I suspect the problem is NP-complete, though in practice it might just
2620 * be doable because faces are limited in size).
2621 * For simplicity, we only consider *pairs* of LINE_UNKNOWNS that are
2622 * known to be identical. If setting them both to YES (or NO) would break
2623 * the clue, set them to NO (or YES). */
2624
2625 for (i = 0; i < g->num_faces; i++) {
2626 int N, yes, no, unknown;
2627 int clue;
2628
2629 if (sstate->face_solved[i])
2630 continue;
2631 clue = state->clues[i];
2632 if (clue < 0)
2633 continue;
2634
2635 N = g->faces[i].order;
2636 yes = sstate->face_yes_count[i];
2637 if (yes + 1 == clue) {
2638 if (face_setall_identical(sstate, i, LINE_NO))
2639 diff = min(diff, DIFF_EASY);
2640 }
2641 no = sstate->face_no_count[i];
2642 if (no + 1 == N - clue) {
2643 if (face_setall_identical(sstate, i, LINE_YES))
2644 diff = min(diff, DIFF_EASY);
2645 }
2646
2647 /* Reload YES count, it might have changed */
2648 yes = sstate->face_yes_count[i];
2649 unknown = N - no - yes;
2650
2651 /* Deductions with small number of LINE_UNKNOWNs, based on overall
2652 * parity of lines. */
2653 diff_tmp = parity_deductions(sstate, g->faces[i].edges,
2654 (clue - yes) % 2, unknown);
2655 diff = min(diff, diff_tmp);
2656 }
2657
2658 /* ------ Dot deductions ------ */
2659 for (i = 0; i < g->num_dots; i++) {
2660 grid_dot *d = g->dots + i;
2661 int N = d->order;
2662 int j;
2663 int yes, no, unknown;
2664 /* Go through dlines, and do any dline<->linedsf deductions wherever
2665 * we find two UNKNOWNS. */
2666 for (j = 0; j < N; j++) {
2667 int dline_index = dline_index_from_dot(g, d, j);
2668 int line1_index;
2669 int line2_index;
2670 int can1, can2, inv1, inv2;
2671 int j2;
2672 line1_index = d->edges[j] - g->edges;
2673 if (state->lines[line1_index] != LINE_UNKNOWN)
2674 continue;
2675 j2 = j + 1;
2676 if (j2 == N) j2 = 0;
2677 line2_index = d->edges[j2] - g->edges;
2678 if (state->lines[line2_index] != LINE_UNKNOWN)
2679 continue;
2680 /* Infer dline flags from linedsf */
2681 can1 = edsf_canonify(sstate->hard->linedsf, line1_index, &inv1);
2682 can2 = edsf_canonify(sstate->hard->linedsf, line2_index, &inv2);
2683 if (can1 == can2 && inv1 != inv2) {
2684 /* These are opposites, so set dline atmostone/atleastone */
2685 if (set_atmostone(dlines, dline_index))
2686 diff = min(diff, DIFF_NORMAL);
2687 if (set_atleastone(dlines, dline_index))
2688 diff = min(diff, DIFF_NORMAL);
2689 continue;
2690 }
2691 /* Infer linedsf from dline flags */
2692 if (is_atmostone(dlines, dline_index)
2693 && is_atleastone(dlines, dline_index)) {
2694 if (merge_lines(sstate, line1_index, line2_index, 1))
2695 diff = min(diff, DIFF_HARD);
2696 }
2697 }
2698
2699 /* Deductions with small number of LINE_UNKNOWNs, based on overall
2700 * parity of lines. */
2701 yes = sstate->dot_yes_count[i];
2702 no = sstate->dot_no_count[i];
2703 unknown = N - yes - no;
2704 diff_tmp = parity_deductions(sstate, d->edges,
2705 yes % 2, unknown);
2706 diff = min(diff, diff_tmp);
2707 }
2708
2709 /* ------ Edge dsf deductions ------ */
2710
2711 /* If the state of a line is known, deduce the state of its canonical line
2712 * too, and vice versa. */
2713 for (i = 0; i < g->num_edges; i++) {
2714 int can, inv;
2715 enum line_state s;
2716 can = edsf_canonify(sstate->hard->linedsf, i, &inv);
2717 if (can == i)
2718 continue;
2719 s = sstate->state->lines[can];
2720 if (s != LINE_UNKNOWN) {
2721 if (solver_set_line(sstate, i, inv ? OPP(s) : s))
2722 diff = min(diff, DIFF_EASY);
2723 } else {
2724 s = sstate->state->lines[i];
2725 if (s != LINE_UNKNOWN) {
2726 if (solver_set_line(sstate, can, inv ? OPP(s) : s))
2727 diff = min(diff, DIFF_EASY);
2728 }
2729 }
2730 }
2731
2732 return diff;
2733 }
2734
2735 static int loop_deductions(solver_state *sstate)
2736 {
2737 int edgecount = 0, clues = 0, satclues = 0, sm1clues = 0;
2738 game_state *state = sstate->state;
2739 grid *g = state->game_grid;
2740 int shortest_chainlen = g->num_dots;
2741 int loop_found = FALSE;
2742 int dots_connected;
2743 int progress = FALSE;
2744 int i;
2745
2746 /*
2747 * Go through the grid and update for all the new edges.
2748 * Since merge_dots() is idempotent, the simplest way to
2749 * do this is just to update for _all_ the edges.
2750 * Also, while we're here, we count the edges.
2751 */
2752 for (i = 0; i < g->num_edges; i++) {
2753 if (state->lines[i] == LINE_YES) {
2754 loop_found |= merge_dots(sstate, i);
2755 edgecount++;
2756 }
2757 }
2758
2759 /*
2760 * Count the clues, count the satisfied clues, and count the
2761 * satisfied-minus-one clues.
2762 */
2763 for (i = 0; i < g->num_faces; i++) {
2764 int c = state->clues[i];
2765 if (c >= 0) {
2766 int o = sstate->face_yes_count[i];
2767 if (o == c)
2768 satclues++;
2769 else if (o == c-1)
2770 sm1clues++;
2771 clues++;
2772 }
2773 }
2774
2775 for (i = 0; i < g->num_dots; ++i) {
2776 dots_connected =
2777 sstate->looplen[dsf_canonify(sstate->dotdsf, i)];
2778 if (dots_connected > 1)
2779 shortest_chainlen = min(shortest_chainlen, dots_connected);
2780 }
2781
2782 assert(sstate->solver_status == SOLVER_INCOMPLETE);
2783
2784 if (satclues == clues && shortest_chainlen == edgecount) {
2785 sstate->solver_status = SOLVER_SOLVED;
2786 /* This discovery clearly counts as progress, even if we haven't
2787 * just added any lines or anything */
2788 progress = TRUE;
2789 goto finished_loop_deductionsing;
2790 }
2791
2792 /*
2793 * Now go through looking for LINE_UNKNOWN edges which
2794 * connect two dots that are already in the same
2795 * equivalence class. If we find one, test to see if the
2796 * loop it would create is a solution.
2797 */
2798 for (i = 0; i < g->num_edges; i++) {
2799 grid_edge *e = g->edges + i;
2800 int d1 = e->dot1 - g->dots;
2801 int d2 = e->dot2 - g->dots;
2802 int eqclass, val;
2803 if (state->lines[i] != LINE_UNKNOWN)
2804 continue;
2805
2806 eqclass = dsf_canonify(sstate->dotdsf, d1);
2807 if (eqclass != dsf_canonify(sstate->dotdsf, d2))
2808 continue;
2809
2810 val = LINE_NO; /* loop is bad until proven otherwise */
2811
2812 /*
2813 * This edge would form a loop. Next
2814 * question: how long would the loop be?
2815 * Would it equal the total number of edges
2816 * (plus the one we'd be adding if we added
2817 * it)?
2818 */
2819 if (sstate->looplen[eqclass] == edgecount + 1) {
2820 int sm1_nearby;
2821
2822 /*
2823 * This edge would form a loop which
2824 * took in all the edges in the entire
2825 * grid. So now we need to work out
2826 * whether it would be a valid solution
2827 * to the puzzle, which means we have to
2828 * check if it satisfies all the clues.
2829 * This means that every clue must be
2830 * either satisfied or satisfied-minus-
2831 * 1, and also that the number of
2832 * satisfied-minus-1 clues must be at
2833 * most two and they must lie on either
2834 * side of this edge.
2835 */
2836 sm1_nearby = 0;
2837 if (e->face1) {
2838 int f = e->face1 - g->faces;
2839 int c = state->clues[f];
2840 if (c >= 0 && sstate->face_yes_count[f] == c - 1)
2841 sm1_nearby++;
2842 }
2843 if (e->face2) {
2844 int f = e->face2 - g->faces;
2845 int c = state->clues[f];
2846 if (c >= 0 && sstate->face_yes_count[f] == c - 1)
2847 sm1_nearby++;
2848 }
2849 if (sm1clues == sm1_nearby &&
2850 sm1clues + satclues == clues) {
2851 val = LINE_YES; /* loop is good! */
2852 }
2853 }
2854
2855 /*
2856 * Right. Now we know that adding this edge
2857 * would form a loop, and we know whether
2858 * that loop would be a viable solution or
2859 * not.
2860 *
2861 * If adding this edge produces a solution,
2862 * then we know we've found _a_ solution but
2863 * we don't know that it's _the_ solution -
2864 * if it were provably the solution then
2865 * we'd have deduced this edge some time ago
2866 * without the need to do loop detection. So
2867 * in this state we return SOLVER_AMBIGUOUS,
2868 * which has the effect that hitting Solve
2869 * on a user-provided puzzle will fill in a
2870 * solution but using the solver to
2871 * construct new puzzles won't consider this
2872 * a reasonable deduction for the user to
2873 * make.
2874 */
2875 progress = solver_set_line(sstate, i, val);
2876 assert(progress == TRUE);
2877 if (val == LINE_YES) {
2878 sstate->solver_status = SOLVER_AMBIGUOUS;
2879 goto finished_loop_deductionsing;
2880 }
2881 }
2882
2883 finished_loop_deductionsing:
2884 return progress ? DIFF_EASY : DIFF_MAX;
2885 }
2886
2887 /* This will return a dynamically allocated solver_state containing the (more)
2888 * solved grid */
2889 static solver_state *solve_game_rec(const solver_state *sstate_start,
2890 int diff)
2891 {
2892 solver_state *sstate, *sstate_saved;
2893 int solver_progress;
2894 game_state *state;
2895
2896 /* Indicates which solver we should call next. This is a sensible starting
2897 * point */
2898 int current_solver = DIFF_EASY, next_solver;
2899 sstate = dup_solver_state(sstate_start);
2900
2901 /* Cache the values of some variables for readability */
2902 state = sstate->state;
2903
2904 sstate_saved = NULL;
2905
2906 solver_progress = FALSE;
2907
2908 check_caches(sstate);
2909
2910 do {
2911 if (sstate->solver_status == SOLVER_MISTAKE)
2912 return sstate;
2913
2914 next_solver = solver_fns[current_solver](sstate);
2915
2916 if (next_solver == DIFF_MAX) {
2917 if (current_solver < diff && current_solver + 1 < DIFF_MAX) {
2918 /* Try next beefier solver */
2919 next_solver = current_solver + 1;
2920 } else {
2921 next_solver = loop_deductions(sstate);
2922 }
2923 }
2924
2925 if (sstate->solver_status == SOLVER_SOLVED ||
2926 sstate->solver_status == SOLVER_AMBIGUOUS) {
2927 /* fprintf(stderr, "Solver completed\n"); */
2928 break;
2929 }
2930
2931 /* Once we've looped over all permitted solvers then the loop
2932 * deductions without making any progress, we'll exit this while loop */
2933 current_solver = next_solver;
2934 } while (current_solver < DIFF_MAX);
2935
2936 if (sstate->solver_status == SOLVER_SOLVED ||
2937 sstate->solver_status == SOLVER_AMBIGUOUS) {
2938 /* s/LINE_UNKNOWN/LINE_NO/g */
2939 array_setall(sstate->state->lines, LINE_UNKNOWN, LINE_NO,
2940 sstate->state->game_grid->num_edges);
2941 return sstate;
2942 }
2943
2944 return sstate;
2945 }
2946
2947 static char *solve_game(game_state *state, game_state *currstate,
2948 char *aux, char **error)
2949 {
2950 char *soln = NULL;
2951 solver_state *sstate, *new_sstate;
2952
2953 sstate = new_solver_state(state, DIFF_MAX);
2954 new_sstate = solve_game_rec(sstate, DIFF_MAX);
2955
2956 if (new_sstate->solver_status == SOLVER_SOLVED) {
2957 soln = encode_solve_move(new_sstate->state);
2958 } else if (new_sstate->solver_status == SOLVER_AMBIGUOUS) {
2959 soln = encode_solve_move(new_sstate->state);
2960 /**error = "Solver found ambiguous solutions"; */
2961 } else {
2962 soln = encode_solve_move(new_sstate->state);
2963 /**error = "Solver failed"; */
2964 }
2965
2966 free_solver_state(new_sstate);
2967 free_solver_state(sstate);
2968
2969 return soln;
2970 }
2971
2972 /* ----------------------------------------------------------------------
2973 * Drawing and mouse-handling
2974 */
2975
2976 static char *interpret_move(game_state *state, game_ui *ui, game_drawstate *ds,
2977 int x, int y, int button)
2978 {
2979 grid *g = state->game_grid;
2980 grid_edge *e;
2981 int i;
2982 char *ret, buf[80];
2983 char button_char = ' ';
2984 enum line_state old_state;
2985
2986 button &= ~MOD_MASK;
2987
2988 /* Convert mouse-click (x,y) to grid coordinates */
2989 x -= BORDER(ds->tilesize);
2990 y -= BORDER(ds->tilesize);
2991 x = x * g->tilesize / ds->tilesize;
2992 y = y * g->tilesize / ds->tilesize;
2993 x += g->lowest_x;
2994 y += g->lowest_y;
2995
2996 e = grid_nearest_edge(g, x, y);
2997 if (e == NULL)
2998 return NULL;
2999
3000 i = e - g->edges;
3001
3002 /* I think it's only possible to play this game with mouse clicks, sorry */
3003 /* Maybe will add mouse drag support some time */
3004 old_state = state->lines[i];
3005
3006 switch (button) {
3007 case LEFT_BUTTON:
3008 switch (old_state) {
3009 case LINE_UNKNOWN:
3010 button_char = 'y';
3011 break;
3012 case LINE_YES:
3013 case LINE_NO:
3014 button_char = 'u';
3015 break;
3016 }
3017 break;
3018 case MIDDLE_BUTTON:
3019 button_char = 'u';
3020 break;
3021 case RIGHT_BUTTON:
3022 switch (old_state) {
3023 case LINE_UNKNOWN:
3024 button_char = 'n';
3025 break;
3026 case LINE_NO:
3027 case LINE_YES:
3028 button_char = 'u';
3029 break;
3030 }
3031 break;
3032 default:
3033 return NULL;
3034 }
3035
3036
3037 sprintf(buf, "%d%c", i, (int)button_char);
3038 ret = dupstr(buf);
3039
3040 return ret;
3041 }
3042
3043 static game_state *execute_move(game_state *state, char *move)
3044 {
3045 int i;
3046 game_state *newstate = dup_game(state);
3047
3048 if (move[0] == 'S') {
3049 move++;
3050 newstate->cheated = TRUE;
3051 }
3052
3053 while (*move) {
3054 i = atoi(move);
3055 move += strspn(move, "1234567890");
3056 switch (*(move++)) {
3057 case 'y':
3058 newstate->lines[i] = LINE_YES;
3059 break;
3060 case 'n':
3061 newstate->lines[i] = LINE_NO;
3062 break;
3063 case 'u':
3064 newstate->lines[i] = LINE_UNKNOWN;
3065 break;
3066 default:
3067 goto fail;
3068 }
3069 }
3070
3071 /*
3072 * Check for completion.
3073 */
3074 if (check_completion(newstate))
3075 newstate->solved = TRUE;
3076
3077 return newstate;
3078
3079 fail:
3080 free_game(newstate);
3081 return NULL;
3082 }
3083
3084 /* ----------------------------------------------------------------------
3085 * Drawing routines.
3086 */
3087
3088 /* Convert from grid coordinates to screen coordinates */
3089 static void grid_to_screen(const game_drawstate *ds, const grid *g,
3090 int grid_x, int grid_y, int *x, int *y)
3091 {
3092 *x = grid_x - g->lowest_x;
3093 *y = grid_y - g->lowest_y;
3094 *x = *x * ds->tilesize / g->tilesize;
3095 *y = *y * ds->tilesize / g->tilesize;
3096 *x += BORDER(ds->tilesize);
3097 *y += BORDER(ds->tilesize);
3098 }
3099
3100 /* Returns (into x,y) position of centre of face for rendering the text clue.
3101 */
3102 static void face_text_pos(const game_drawstate *ds, const grid *g,
3103 const grid_face *f, int *x, int *y)
3104 {
3105 int i;
3106
3107 /* Simplest solution is the centroid. Might not work in some cases. */
3108
3109 /* Another algorithm to look into:
3110 * Find the midpoints of the sides, find the bounding-box,
3111 * then take the centre of that. */
3112
3113 /* Best solution probably involves incentres (inscribed circles) */
3114
3115 int sx = 0, sy = 0; /* sums */
3116 for (i = 0; i < f->order; i++) {
3117 grid_dot *d = f->dots[i];
3118 sx += d->x;
3119 sy += d->y;
3120 }
3121 sx /= f->order;
3122 sy /= f->order;
3123
3124 /* convert to screen coordinates */
3125 grid_to_screen(ds, g, sx, sy, x, y);
3126 }
3127
3128 static void game_redraw(drawing *dr, game_drawstate *ds, game_state *oldstate,
3129 game_state *state, int dir, game_ui *ui,
3130 float animtime, float flashtime)
3131 {
3132 grid *g = state->game_grid;
3133 int border = BORDER(ds->tilesize);
3134 int i, n;
3135 char c[2];
3136 int line_colour, flash_changed;
3137 int clue_mistake;
3138 int clue_satisfied;
3139
3140 if (!ds->started) {
3141 /*
3142 * The initial contents of the window are not guaranteed and
3143 * can vary with front ends. To be on the safe side, all games
3144 * should start by drawing a big background-colour rectangle
3145 * covering the whole window.
3146 */
3147 int grid_width = g->highest_x - g->lowest_x;
3148 int grid_height = g->highest_y - g->lowest_y;
3149 int w = grid_width * ds->tilesize / g->tilesize;
3150 int h = grid_height * ds->tilesize / g->tilesize;
3151 draw_rect(dr, 0, 0, w + 2 * border + 1, h + 2 * border + 1,
3152 COL_BACKGROUND);
3153
3154 /* Draw clues */
3155 for (i = 0; i < g->num_faces; i++) {
3156 grid_face *f;
3157 int x, y;
3158
3159 c[0] = CLUE2CHAR(state->clues[i]);
3160 c[1] = '\0';
3161 f = g->faces + i;
3162 face_text_pos(ds, g, f, &x, &y);
3163 draw_text(dr, x, y, FONT_VARIABLE, ds->tilesize/2,
3164 ALIGN_VCENTRE | ALIGN_HCENTRE, COL_FOREGROUND, c);
3165 }
3166 draw_update(dr, 0, 0, w + 2 * border, h + 2 * border);
3167 }
3168
3169 if (flashtime > 0 &&
3170 (flashtime <= FLASH_TIME/3 ||
3171 flashtime >= FLASH_TIME*2/3)) {
3172 flash_changed = !ds->flashing;
3173 ds->flashing = TRUE;
3174 } else {
3175 flash_changed = ds->flashing;
3176 ds->flashing = FALSE;
3177 }
3178
3179 /* Some platforms may perform anti-aliasing, which may prevent clean
3180 * repainting of lines when the colour is changed.
3181 * If a line needs to be over-drawn in a different colour, erase a
3182 * bounding-box around the line, then flag all nearby objects for redraw.
3183 */
3184 if (ds->started) {
3185 const char redraw_flag = (char)(1<<7);
3186 for (i = 0; i < g->num_edges; i++) {
3187 char prev_ds = (ds->lines[i] & ~redraw_flag);
3188 char new_ds = state->lines[i];
3189 if (state->line_errors[i])
3190 new_ds = DS_LINE_ERROR;
3191
3192 /* If we're changing state, AND
3193 * the previous state was a coloured line */
3194 if ((prev_ds != new_ds) && (prev_ds != LINE_NO)) {
3195 grid_edge *e = g->edges + i;
3196 int x1 = e->dot1->x;
3197 int y1 = e->dot1->y;
3198 int x2 = e->dot2->x;
3199 int y2 = e->dot2->y;
3200 int xmin, xmax, ymin, ymax;
3201 int j;
3202 grid_to_screen(ds, g, x1, y1, &x1, &y1);
3203 grid_to_screen(ds, g, x2, y2, &x2, &y2);
3204 /* Allow extra margin for dots, and thickness of lines */
3205 xmin = min(x1, x2) - 2;
3206 xmax = max(x1, x2) + 2;
3207 ymin = min(y1, y2) - 2;
3208 ymax = max(y1, y2) + 2;
3209 /* For testing, I find it helpful to change COL_BACKGROUND
3210 * to COL_SATISFIED here. */
3211 draw_rect(dr, xmin, ymin, xmax - xmin + 1, ymax - ymin + 1,
3212 COL_BACKGROUND);
3213 draw_update(dr, xmin, ymin, xmax - xmin + 1, ymax - ymin + 1);
3214
3215 /* Mark nearby lines for redraw */
3216 for (j = 0; j < e->dot1->order; j++)
3217 ds->lines[e->dot1->edges[j] - g->edges] |= redraw_flag;
3218 for (j = 0; j < e->dot2->order; j++)
3219 ds->lines[e->dot2->edges[j] - g->edges] |= redraw_flag;
3220 /* Mark nearby clues for redraw. Use a value that is
3221 * neither TRUE nor FALSE for this. */
3222 if (e->face1)
3223 ds->clue_error[e->face1 - g->faces] = 2;
3224 if (e->face2)
3225 ds->clue_error[e->face2 - g->faces] = 2;
3226 }
3227 }
3228 }
3229
3230 /* Redraw clue colours if necessary */
3231 for (i = 0; i < g->num_faces; i++) {
3232 grid_face *f = g->faces + i;
3233 int sides = f->order;
3234 int j;
3235 n = state->clues[i];
3236 if (n < 0)
3237 continue;
3238
3239 c[0] = CLUE2CHAR(n);
3240 c[1] = '\0';
3241
3242 clue_mistake = (face_order(state, i, LINE_YES) > n ||
3243 face_order(state, i, LINE_NO ) > (sides-n));
3244
3245 clue_satisfied = (face_order(state, i, LINE_YES) == n &&
3246 face_order(state, i, LINE_NO ) == (sides-n));
3247
3248 if (clue_mistake != ds->clue_error[i]
3249 || clue_satisfied != ds->clue_satisfied[i]) {
3250 int x, y;
3251 face_text_pos(ds, g, f, &x, &y);
3252 /* There seems to be a certain amount of trial-and-error
3253 * involved in working out the correct bounding-box for
3254 * the text. */
3255 draw_rect(dr, x - ds->tilesize/4 - 1, y - ds->tilesize/4 - 3,
3256 ds->tilesize/2 + 2, ds->tilesize/2 + 5,
3257 COL_BACKGROUND);
3258 draw_text(dr, x, y,
3259 FONT_VARIABLE, ds->tilesize/2,
3260 ALIGN_VCENTRE | ALIGN_HCENTRE,
3261 clue_mistake ? COL_MISTAKE :
3262 clue_satisfied ? COL_SATISFIED : COL_FOREGROUND, c);
3263 draw_update(dr, x - ds->tilesize/4 - 1, y - ds->tilesize/4 - 3,
3264 ds->tilesize/2 + 2, ds->tilesize/2 + 5);
3265
3266 ds->clue_error[i] = clue_mistake;
3267 ds->clue_satisfied[i] = clue_satisfied;
3268
3269 /* Sometimes, the bounding-box encroaches into the surrounding
3270 * lines (particularly if the window is resized fairly small).
3271 * So redraw them. */
3272 for (j = 0; j < f->order; j++)
3273 ds->lines[f->edges[j] - g->edges] = -1;
3274 }
3275 }
3276
3277 /* Lines */
3278 for (i = 0; i < g->num_edges; i++) {
3279 grid_edge *e = g->edges + i;
3280 int x1, x2, y1, y2;
3281 int xmin, ymin, xmax, ymax;
3282 char new_ds, need_draw;
3283 new_ds = state->lines[i];
3284 if (state->line_errors[i])
3285 new_ds = DS_LINE_ERROR;
3286 need_draw = (new_ds != ds->lines[i]) ? TRUE : FALSE;
3287 if (flash_changed && (state->lines[i] == LINE_YES))
3288 need_draw = TRUE;
3289 if (!ds->started)
3290 need_draw = TRUE; /* draw everything at the start */
3291 ds->lines[i] = new_ds;
3292 if (!need_draw)
3293 continue;
3294 if (state->line_errors[i])
3295 line_colour = COL_MISTAKE;
3296 else if (state->lines[i] == LINE_UNKNOWN)
3297 line_colour = COL_LINEUNKNOWN;
3298 else if (state->lines[i] == LINE_NO)
3299 line_colour = COL_BACKGROUND;
3300 else if (ds->flashing)
3301 line_colour = COL_HIGHLIGHT;
3302 else
3303 line_colour = COL_FOREGROUND;
3304
3305 /* Convert from grid to screen coordinates */
3306 grid_to_screen(ds, g, e->dot1->x, e->dot1->y, &x1, &y1);
3307 grid_to_screen(ds, g, e->dot2->x, e->dot2->y, &x2, &y2);
3308
3309 xmin = min(x1, x2);
3310 xmax = max(x1, x2);
3311 ymin = min(y1, y2);
3312 ymax = max(y1, y2);
3313
3314 if (line_colour != COL_BACKGROUND) {
3315 /* (dx, dy) points roughly from (x1, y1) to (x2, y2).
3316 * The line is then "fattened" in a (roughly) perpendicular
3317 * direction to create a thin rectangle. */
3318 int dx = (x1 > x2) ? -1 : ((x1 < x2) ? 1 : 0);
3319 int dy = (y1 > y2) ? -1 : ((y1 < y2) ? 1 : 0);
3320 int points[8];
3321 points[0] = x1 + dy;
3322 points[1] = y1 - dx;
3323 points[2] = x1 - dy;
3324 points[3] = y1 + dx;
3325 points[4] = x2 - dy;
3326 points[5] = y2 + dx;
3327 points[6] = x2 + dy;
3328 points[7] = y2 - dx;
3329 draw_polygon(dr, points, 4, line_colour, line_colour);
3330 }
3331 if (ds->started) {
3332 /* Draw dots at ends of the line */
3333 draw_circle(dr, x1, y1, 2, COL_FOREGROUND, COL_FOREGROUND);
3334 draw_circle(dr, x2, y2, 2, COL_FOREGROUND, COL_FOREGROUND);
3335 }
3336 draw_update(dr, xmin-2, ymin-2, xmax - xmin + 4, ymax - ymin + 4);
3337 }
3338
3339 /* Draw dots */
3340 if (!ds->started) {
3341 for (i = 0; i < g->num_dots; i++) {
3342 grid_dot *d = g->dots + i;
3343 int x, y;
3344 grid_to_screen(ds, g, d->x, d->y, &x, &y);
3345 draw_circle(dr, x, y, 2, COL_FOREGROUND, COL_FOREGROUND);
3346 }
3347 }
3348 ds->started = TRUE;
3349 }
3350
3351 static float game_flash_length(game_state *oldstate, game_state *newstate,
3352 int dir, game_ui *ui)
3353 {
3354 if (!oldstate->solved && newstate->solved &&
3355 !oldstate->cheated && !newstate->cheated) {
3356 return FLASH_TIME;
3357 }
3358
3359 return 0.0F;
3360 }
3361
3362 static void game_print_size(game_params *params, float *x, float *y)
3363 {
3364 int pw, ph;
3365
3366 /*
3367 * I'll use 7mm "squares" by default.
3368 */
3369 game_compute_size(params, 700, &pw, &ph);
3370 *x = pw / 100.0F;
3371 *y = ph / 100.0F;
3372 }
3373
3374 static void game_print(drawing *dr, game_state *state, int tilesize)
3375 {
3376 int ink = print_mono_colour(dr, 0);
3377 int i;
3378 game_drawstate ads, *ds = &ads;
3379 grid *g = state->game_grid;
3380
3381 game_set_size(dr, ds, NULL, tilesize);
3382
3383 for (i = 0; i < g->num_dots; i++) {
3384 int x, y;
3385 grid_to_screen(ds, g, g->dots[i].x, g->dots[i].y, &x, &y);
3386 draw_circle(dr, x, y, ds->tilesize / 15, ink, ink);
3387 }
3388
3389 /*
3390 * Clues.
3391 */
3392 for (i = 0; i < g->num_faces; i++) {
3393 grid_face *f = g->faces + i;
3394 int clue = state->clues[i];
3395 if (clue >= 0) {
3396 char c[2];
3397 int x, y;
3398 c[0] = CLUE2CHAR(clue);
3399 c[1] = '\0';
3400 face_text_pos(ds, g, f, &x, &y);
3401 draw_text(dr, x, y,
3402 FONT_VARIABLE, ds->tilesize / 2,
3403 ALIGN_VCENTRE | ALIGN_HCENTRE, ink, c);
3404 }
3405 }
3406
3407 /*
3408 * Lines.
3409 */
3410 for (i = 0; i < g->num_edges; i++) {
3411 int thickness = (state->lines[i] == LINE_YES) ? 30 : 150;
3412 grid_edge *e = g->edges + i;
3413 int x1, y1, x2, y2;
3414 grid_to_screen(ds, g, e->dot1->x, e->dot1->y, &x1, &y1);
3415 grid_to_screen(ds, g, e->dot2->x, e->dot2->y, &x2, &y2);
3416 if (state->lines[i] == LINE_YES)
3417 {
3418 /* (dx, dy) points from (x1, y1) to (x2, y2).
3419 * The line is then "fattened" in a perpendicular
3420 * direction to create a thin rectangle. */
3421 double d = sqrt(SQ((double)x1 - x2) + SQ((double)y1 - y2));
3422 double dx = (x2 - x1) / d;
3423 double dy = (y2 - y1) / d;
3424 int points[8];
3425
3426 dx = (dx * ds->tilesize) / thickness;
3427 dy = (dy * ds->tilesize) / thickness;
3428 points[0] = x1 + (int)dy;
3429 points[1] = y1 - (int)dx;
3430 points[2] = x1 - (int)dy;
3431 points[3] = y1 + (int)dx;
3432 points[4] = x2 - (int)dy;
3433 points[5] = y2 + (int)dx;
3434 points[6] = x2 + (int)dy;
3435 points[7] = y2 - (int)dx;
3436 draw_polygon(dr, points, 4, ink, ink);
3437 }
3438 else
3439 {
3440 /* Draw a dotted line */
3441 int divisions = 6;
3442 int j;
3443 for (j = 1; j < divisions; j++) {
3444 /* Weighted average */
3445 int x = (x1 * (divisions -j) + x2 * j) / divisions;
3446 int y = (y1 * (divisions -j) + y2 * j) / divisions;
3447 draw_circle(dr, x, y, ds->tilesize / thickness, ink, ink);
3448 }
3449 }
3450 }
3451 }
3452
3453 #ifdef COMBINED
3454 #define thegame loopy
3455 #endif
3456
3457 const struct game thegame = {
3458 "Loopy", "games.loopy", "loopy",
3459 default_params,
3460 game_fetch_preset,
3461 decode_params,
3462 encode_params,
3463 free_params,
3464 dup_params,
3465 TRUE, game_configure, custom_params,
3466 validate_params,
3467 new_game_desc,
3468 validate_desc,
3469 new_game,
3470 dup_game,
3471 free_game,
3472 1, solve_game,
3473 TRUE, game_can_format_as_text_now, game_text_format,
3474 new_ui,
3475 free_ui,
3476 encode_ui,
3477 decode_ui,
3478 game_changed_state,
3479 interpret_move,
3480 execute_move,
3481 PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
3482 game_colours,
3483 game_new_drawstate,
3484 game_free_drawstate,
3485 game_redraw,
3486 game_anim_length,
3487 game_flash_length,
3488 TRUE, FALSE, game_print_size, game_print,
3489 FALSE /* wants_statusbar */,
3490 FALSE, game_timing_state,
3491 0, /* mouse_priorities */
3492 };