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