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