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