Mike Pinna has done some major reworking of the Loopy solver, giving
[sgt/puzzles] / loopy.c
1 /*
2 * loopy.c: An implementation of the Nikoli game 'Loop the loop'.
3 * (c) Mike Pinna, 2005, 2006
4 *
5 * vim: set shiftwidth=4 :set textwidth=80:
6 */
7
8 /*
9 * TODO:
10 *
11 * - Setting very high recursion depth seems to cause memory munching: are we
12 * recursing before checking completion, by any chance?
13 *
14 * - There's an interesting deductive technique which makes use of topology
15 * rather than just graph theory. Each _square_ in the grid is either inside
16 * or outside the loop; you can tell that two squares are on the same side
17 * of the loop if they're separated by an x (or, more generally, by a path
18 * crossing no LINE_UNKNOWNs and an even number of LINE_YESes), and on the
19 * opposite side of the loop if they're separated by a line (or an odd
20 * number of LINE_YESes and no LINE_UNKNOWNs). Oh, and any square separated
21 * from the outside of the grid by a LINE_YES or a LINE_NO is on the inside
22 * or outside respectively. So if you can track this for all squares, you
23 * figure out the state of the line between a pair once their relative
24 * insideness is known.
25 *
26 * - (Just a speed optimisation.) Consider some todo list queue where every
27 * time we modify something we mark it for consideration by other bits of
28 * the solver, to save iteration over things that have already been done.
29 */
30
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <assert.h>
35 #include <ctype.h>
36 #include <math.h>
37
38 #include "puzzles.h"
39 #include "tree234.h"
40
41 /* Debugging options */
42 /*#define DEBUG_CACHES*/
43 /*#define SHOW_WORKING*/
44
45 /* ----------------------------------------------------------------------
46 * Struct, enum and function declarations
47 */
48
49 enum {
50 COL_BACKGROUND,
51 COL_FOREGROUND,
52 COL_HIGHLIGHT,
53 COL_MISTAKE,
54 NCOLOURS
55 };
56
57 struct game_state {
58 int w, h;
59
60 /* Put -1 in a square that doesn't get a clue */
61 char *clues;
62
63 /* Arrays of line states, stored left-to-right, top-to-bottom */
64 char *hl, *vl;
65
66 int solved;
67 int cheated;
68
69 int recursion_depth;
70 };
71
72 enum solver_status {
73 SOLVER_SOLVED, /* This is the only solution the solver could find */
74 SOLVER_MISTAKE, /* This is definitely not a solution */
75 SOLVER_AMBIGUOUS, /* This _might_ be an ambiguous solution */
76 SOLVER_INCOMPLETE /* This may be a partial solution */
77 };
78
79 typedef struct normal {
80 char *dot_atleastone;
81 char *dot_atmostone;
82 } normal_mode_state;
83
84 typedef struct hard {
85 int *linedsf;
86 } hard_mode_state;
87
88 typedef struct solver_state {
89 game_state *state;
90 int recursion_remaining;
91 enum solver_status solver_status;
92 /* NB looplen is the number of dots that are joined together at a point, ie a
93 * looplen of 1 means there are no lines to a particular dot */
94 int *looplen;
95
96 /* caches */
97 char *dot_yescount;
98 char *dot_nocount;
99 char *square_yescount;
100 char *square_nocount;
101 char *dot_solved, *square_solved;
102 int *dotdsf;
103
104 normal_mode_state *normal;
105 hard_mode_state *hard;
106 } solver_state;
107
108 /*
109 * Difficulty levels. I do some macro ickery here to ensure that my
110 * enum and the various forms of my name list always match up.
111 */
112
113 #define DIFFLIST(A) \
114 A(EASY,Easy,e,easy_mode_deductions) \
115 A(NORMAL,Normal,n,normal_mode_deductions) \
116 A(HARD,Hard,h,hard_mode_deductions)
117 #define ENUM(upper,title,lower,fn) DIFF_ ## upper,
118 #define TITLE(upper,title,lower,fn) #title,
119 #define ENCODE(upper,title,lower,fn) #lower
120 #define CONFIG(upper,title,lower,fn) ":" #title
121 #define SOLVER_FN_DECL(upper,title,lower,fn) static int fn(solver_state *);
122 #define SOLVER_FN(upper,title,lower,fn) &fn,
123 enum diff { DIFFLIST(ENUM) DIFF_MAX };
124 static char const *const diffnames[] = { DIFFLIST(TITLE) };
125 static char const diffchars[] = DIFFLIST(ENCODE);
126 #define DIFFCONFIG DIFFLIST(CONFIG)
127 DIFFLIST(SOLVER_FN_DECL);
128 static int (*(solver_fns[]))(solver_state *) = { DIFFLIST(SOLVER_FN) };
129
130 struct game_params {
131 int w, h;
132 enum diff diff;
133 int rec;
134 };
135
136 enum line_state { LINE_YES, LINE_UNKNOWN, LINE_NO };
137
138 #define OPP(state) \
139 (2 - state)
140
141 enum direction { UP, LEFT, RIGHT, DOWN };
142
143 #define OPP_DIR(dir) \
144 (3 - dir)
145
146 struct game_drawstate {
147 int started;
148 int tilesize, linewidth;
149 int flashing;
150 char *hl, *vl;
151 char *clue_error;
152 };
153
154 static char *game_text_format(game_state *state);
155 static char *state_to_text(const game_state *state);
156 static char *validate_desc(game_params *params, char *desc);
157 static int get_line_status_from_point(const game_state *state,
158 int x, int y, enum direction d);
159 static int dot_order(const game_state* state, int i, int j, char line_type);
160 static int square_order(const game_state* state, int i, int j, char line_type);
161 static solver_state *solve_game_rec(const solver_state *sstate,
162 enum diff diff);
163
164 #ifdef DEBUG_CACHES
165 static void check_caches(const solver_state* sstate);
166 #else
167 #define check_caches(s)
168 #endif
169
170 /* ----------------------------------------------------------------------
171 * Preprocessor magic
172 */
173
174 /* General constants */
175 #define PREFERRED_TILE_SIZE 32
176 #define TILE_SIZE (ds->tilesize)
177 #define LINEWIDTH (ds->linewidth)
178 #define BORDER (TILE_SIZE / 2)
179 #define FLASH_TIME 0.5F
180
181 /* Counts of various things that we're interested in */
182 #define HL_COUNT(state) ((state)->w * ((state)->h + 1))
183 #define VL_COUNT(state) (((state)->w + 1) * (state)->h)
184 #define LINE_COUNT(state) (HL_COUNT(state) + VL_COUNT(state))
185 #define DOT_COUNT(state) (((state)->w + 1) * ((state)->h + 1))
186 #define SQUARE_COUNT(state) ((state)->w * (state)->h)
187
188 /* For indexing into arrays */
189 #define DOT_INDEX(state, x, y) ((x) + ((state)->w + 1) * (y))
190 #define SQUARE_INDEX(state, x, y) ((x) + ((state)->w) * (y))
191 #define HL_INDEX(state, x, y) SQUARE_INDEX(state, x, y)
192 #define VL_INDEX(state, x, y) DOT_INDEX(state, x, y)
193
194 /* Useful utility functions */
195 #define LEGAL_DOT(state, i, j) ((i) >= 0 && (j) >= 0 && \
196 (i) <= (state)->w && (j) <= (state)->h)
197 #define LEGAL_SQUARE(state, i, j) ((i) >= 0 && (j) >= 0 && \
198 (i) < (state)->w && (j) < (state)->h)
199
200 #define CLUE_AT(state, i, j) (LEGAL_SQUARE(state, i, j) ? \
201 LV_CLUE_AT(state, i, j) : -1)
202
203 #define LV_CLUE_AT(state, i, j) ((state)->clues[SQUARE_INDEX(state, i, j)])
204
205 #define BIT_SET(field, bit) ((field) & (1<<(bit)))
206
207 #define SET_BIT(field, bit) (BIT_SET(field, bit) ? FALSE : \
208 ((field) |= (1<<(bit)), TRUE))
209
210 #define CLEAR_BIT(field, bit) (BIT_SET(field, bit) ? \
211 ((field) &= ~(1<<(bit)), TRUE) : FALSE)
212
213 #define DIR2STR(d) \
214 ((d == UP) ? "up" : \
215 (d == DOWN) ? "down" : \
216 (d == LEFT) ? "left" : \
217 (d == RIGHT) ? "right" : "oops")
218
219 #define CLUE2CHAR(c) \
220 ((c < 0) ? ' ' : c + '0')
221
222 /* Lines that have particular relationships with given dots or squares */
223 #define ABOVE_SQUARE(state, i, j) ((state)->hl[(i) + (state)->w * (j)])
224 #define BELOW_SQUARE(state, i, j) ABOVE_SQUARE(state, i, (j)+1)
225 #define LEFTOF_SQUARE(state, i, j) ((state)->vl[(i) + ((state)->w + 1) * (j)])
226 #define RIGHTOF_SQUARE(state, i, j) LEFTOF_SQUARE(state, (i)+1, j)
227
228 /*
229 * These macros return rvalues only, but can cope with being passed
230 * out-of-range coordinates.
231 */
232 /* XXX replace these with functions so we can create an array of function
233 * pointers for nicer iteration over them. This could probably be done with
234 * loads of other things for eliminating many nasty hacks. */
235 #define ABOVE_DOT(state, i, j) ((!LEGAL_DOT(state, i, j) || j <= 0) ? \
236 LINE_NO : LV_ABOVE_DOT(state, i, j))
237 #define BELOW_DOT(state, i, j) ((!LEGAL_DOT(state, i, j) || j >= (state)->h) ? \
238 LINE_NO : LV_BELOW_DOT(state, i, j))
239
240 #define LEFTOF_DOT(state, i, j) ((!LEGAL_DOT(state, i, j) || i <= 0) ? \
241 LINE_NO : LV_LEFTOF_DOT(state, i, j))
242 #define RIGHTOF_DOT(state, i, j) ((!LEGAL_DOT(state, i, j) || i >= (state)->w)? \
243 LINE_NO : LV_RIGHTOF_DOT(state, i, j))
244
245 /*
246 * These macros expect to be passed valid coordinates, and return
247 * lvalues.
248 */
249 #define LV_BELOW_DOT(state, i, j) ((state)->vl[VL_INDEX(state, i, j)])
250 #define LV_ABOVE_DOT(state, i, j) LV_BELOW_DOT(state, i, (j)-1)
251
252 #define LV_RIGHTOF_DOT(state, i, j) ((state)->hl[HL_INDEX(state, i, j)])
253 #define LV_LEFTOF_DOT(state, i, j) LV_RIGHTOF_DOT(state, (i)-1, j)
254
255 /* Counts of interesting things */
256 #define DOT_YES_COUNT(sstate, i, j) \
257 ((sstate)->dot_yescount[DOT_INDEX((sstate)->state, i, j)])
258
259 #define DOT_NO_COUNT(sstate, i, j) \
260 ((sstate)->dot_nocount[DOT_INDEX((sstate)->state, i, j)])
261
262 #define SQUARE_YES_COUNT(sstate, i, j) \
263 ((sstate)->square_yescount[SQUARE_INDEX((sstate)->state, i, j)])
264
265 #define SQUARE_NO_COUNT(sstate, i, j) \
266 ((sstate)->square_nocount[SQUARE_INDEX((sstate)->state, i, j)])
267
268 /* Iterators. NB these iterate over height more slowly than over width so that
269 * the elements come out in 'reading' order */
270 /* XXX considering adding a 'current' element to each of these which gets the
271 * address of the current dot, say. But expecting we'd need more than that
272 * most of the time. */
273 #define FORALL(i, j, w, h) \
274 for ((j) = 0; (j) < (h); ++(j)) \
275 for ((i) = 0; (i) < (w); ++(i))
276
277 #define FORALL_DOTS(state, i, j) \
278 FORALL(i, j, (state)->w + 1, (state)->h + 1)
279
280 #define FORALL_SQUARES(state, i, j) \
281 FORALL(i, j, (state)->w, (state)->h)
282
283 #define FORALL_HL(state, i, j) \
284 FORALL(i, j, (state)->w, (state)->h+1)
285
286 #define FORALL_VL(state, i, j) \
287 FORALL(i, j, (state)->w+1, (state)->h)
288
289 /* ----------------------------------------------------------------------
290 * General struct manipulation and other straightforward code
291 */
292
293 static game_state *dup_game(game_state *state)
294 {
295 game_state *ret = snew(game_state);
296
297 ret->h = state->h;
298 ret->w = state->w;
299 ret->solved = state->solved;
300 ret->cheated = state->cheated;
301
302 ret->clues = snewn(SQUARE_COUNT(state), char);
303 memcpy(ret->clues, state->clues, SQUARE_COUNT(state));
304
305 ret->hl = snewn(HL_COUNT(state), char);
306 memcpy(ret->hl, state->hl, HL_COUNT(state));
307
308 ret->vl = snewn(VL_COUNT(state), char);
309 memcpy(ret->vl, state->vl, VL_COUNT(state));
310
311 ret->recursion_depth = state->recursion_depth;
312
313 return ret;
314 }
315
316 static void free_game(game_state *state)
317 {
318 if (state) {
319 sfree(state->clues);
320 sfree(state->hl);
321 sfree(state->vl);
322 sfree(state);
323 }
324 }
325
326 static solver_state *new_solver_state(const game_state *state, enum diff diff) {
327 int i, j;
328 solver_state *ret = snew(solver_state);
329
330 ret->state = dup_game((game_state *)state);
331
332 ret->recursion_remaining = state->recursion_depth;
333 ret->solver_status = SOLVER_INCOMPLETE;
334
335 ret->dotdsf = snew_dsf(DOT_COUNT(state));
336 ret->looplen = snewn(DOT_COUNT(state), int);
337
338 for (i = 0; i < DOT_COUNT(state); i++) {
339 ret->looplen[i] = 1;
340 }
341
342 ret->dot_solved = snewn(DOT_COUNT(state), char);
343 ret->square_solved = snewn(SQUARE_COUNT(state), char);
344 memset(ret->dot_solved, FALSE, DOT_COUNT(state));
345 memset(ret->square_solved, FALSE, SQUARE_COUNT(state));
346
347 ret->dot_yescount = snewn(DOT_COUNT(state), char);
348 memset(ret->dot_yescount, 0, DOT_COUNT(state));
349 ret->dot_nocount = snewn(DOT_COUNT(state), char);
350 memset(ret->dot_nocount, 0, DOT_COUNT(state));
351 ret->square_yescount = snewn(SQUARE_COUNT(state), char);
352 memset(ret->square_yescount, 0, SQUARE_COUNT(state));
353 ret->square_nocount = snewn(SQUARE_COUNT(state), char);
354 memset(ret->square_nocount, 0, SQUARE_COUNT(state));
355
356 /* dot_nocount needs special initialisation as we define lines coming off
357 * dots on edges as fixed at NO */
358
359 FORALL_DOTS(state, i, j) {
360 if (i == 0 || i == state->w)
361 ++ret->dot_nocount[DOT_INDEX(state, i, j)];
362 if (j == 0 || j == state->h)
363 ++ret->dot_nocount[DOT_INDEX(state, i, j)];
364 }
365
366 if (diff < DIFF_NORMAL) {
367 ret->normal = NULL;
368 } else {
369 ret->normal = snew(normal_mode_state);
370
371 ret->normal->dot_atmostone = snewn(DOT_COUNT(state), char);
372 memset(ret->normal->dot_atmostone, 0, DOT_COUNT(state));
373 ret->normal->dot_atleastone = snewn(DOT_COUNT(state), char);
374 memset(ret->normal->dot_atleastone, 0, DOT_COUNT(state));
375 }
376
377 if (diff < DIFF_HARD) {
378 ret->hard = NULL;
379 } else {
380 ret->hard = snew(hard_mode_state);
381 ret->hard->linedsf = snew_dsf(LINE_COUNT(state));
382 }
383
384 return ret;
385 }
386
387 static void free_solver_state(solver_state *sstate) {
388 if (sstate) {
389 free_game(sstate->state);
390 sfree(sstate->dotdsf);
391 sfree(sstate->looplen);
392 sfree(sstate->dot_solved);
393 sfree(sstate->square_solved);
394 sfree(sstate->dot_yescount);
395 sfree(sstate->dot_nocount);
396 sfree(sstate->square_yescount);
397 sfree(sstate->square_nocount);
398
399 if (sstate->normal) {
400 sfree(sstate->normal->dot_atleastone);
401 sfree(sstate->normal->dot_atmostone);
402 sfree(sstate->normal);
403 }
404
405 if (sstate->hard) {
406 sfree(sstate->hard->linedsf);
407 sfree(sstate->hard);
408 }
409
410 sfree(sstate);
411 }
412 }
413
414 static solver_state *dup_solver_state(const solver_state *sstate) {
415 game_state *state;
416
417 solver_state *ret = snew(solver_state);
418
419 ret->state = state = dup_game(sstate->state);
420
421 ret->recursion_remaining = sstate->recursion_remaining;
422 ret->solver_status = sstate->solver_status;
423
424 ret->dotdsf = snewn(DOT_COUNT(state), int);
425 ret->looplen = snewn(DOT_COUNT(state), int);
426 memcpy(ret->dotdsf, sstate->dotdsf,
427 DOT_COUNT(state) * sizeof(int));
428 memcpy(ret->looplen, sstate->looplen,
429 DOT_COUNT(state) * sizeof(int));
430
431 ret->dot_solved = snewn(DOT_COUNT(state), char);
432 ret->square_solved = snewn(SQUARE_COUNT(state), char);
433 memcpy(ret->dot_solved, sstate->dot_solved,
434 DOT_COUNT(state));
435 memcpy(ret->square_solved, sstate->square_solved,
436 SQUARE_COUNT(state));
437
438 ret->dot_yescount = snewn(DOT_COUNT(state), char);
439 memcpy(ret->dot_yescount, sstate->dot_yescount,
440 DOT_COUNT(state));
441 ret->dot_nocount = snewn(DOT_COUNT(state), char);
442 memcpy(ret->dot_nocount, sstate->dot_nocount,
443 DOT_COUNT(state));
444
445 ret->square_yescount = snewn(SQUARE_COUNT(state), char);
446 memcpy(ret->square_yescount, sstate->square_yescount,
447 SQUARE_COUNT(state));
448 ret->square_nocount = snewn(SQUARE_COUNT(state), char);
449 memcpy(ret->square_nocount, sstate->square_nocount,
450 SQUARE_COUNT(state));
451
452 if (sstate->normal) {
453 ret->normal = snew(normal_mode_state);
454 ret->normal->dot_atmostone = snewn(DOT_COUNT(state), char);
455 memcpy(ret->normal->dot_atmostone, sstate->normal->dot_atmostone,
456 DOT_COUNT(state));
457
458 ret->normal->dot_atleastone = snewn(DOT_COUNT(state), char);
459 memcpy(ret->normal->dot_atleastone, sstate->normal->dot_atleastone,
460 DOT_COUNT(state));
461 } else {
462 ret->normal = NULL;
463 }
464
465 if (sstate->hard) {
466 ret->hard = snew(hard_mode_state);
467 ret->hard->linedsf = snewn(LINE_COUNT(state), int);
468 memcpy(ret->hard->linedsf, sstate->hard->linedsf,
469 LINE_COUNT(state) * sizeof(int));
470 } else {
471 ret->hard = NULL;
472 }
473
474 return ret;
475 }
476
477 static game_params *default_params(void)
478 {
479 game_params *ret = snew(game_params);
480
481 #ifdef SLOW_SYSTEM
482 ret->h = 4;
483 ret->w = 4;
484 #else
485 ret->h = 10;
486 ret->w = 10;
487 #endif
488 ret->diff = DIFF_EASY;
489 ret->rec = 0;
490
491 return ret;
492 }
493
494 static game_params *dup_params(game_params *params)
495 {
496 game_params *ret = snew(game_params);
497 *ret = *params; /* structure copy */
498 return ret;
499 }
500
501 static const game_params presets[] = {
502 { 4, 4, DIFF_EASY, 0 },
503 { 4, 4, DIFF_NORMAL, 0 },
504 { 4, 4, DIFF_HARD, 0 },
505 { 7, 7, DIFF_EASY, 0 },
506 { 7, 7, DIFF_NORMAL, 0 },
507 { 7, 7, DIFF_HARD, 0 },
508 { 10, 10, DIFF_EASY, 0 },
509 { 10, 10, DIFF_NORMAL, 0 },
510 { 10, 10, DIFF_HARD, 0 },
511 #ifndef SLOW_SYSTEM
512 { 15, 15, DIFF_EASY, 0 },
513 { 15, 15, DIFF_NORMAL, 0 },
514 { 15, 15, DIFF_HARD, 0 },
515 { 30, 20, DIFF_EASY, 0 },
516 { 30, 20, DIFF_NORMAL, 0 },
517 { 30, 20, DIFF_HARD, 0 }
518 #endif
519 };
520
521 static int game_fetch_preset(int i, char **name, game_params **params)
522 {
523 const game_params *tmppar;
524 char buf[80];
525
526 if (i < 0 || i >= lenof(presets))
527 return FALSE;
528
529 tmppar = &presets[i];
530 *params = dup_params((game_params *)tmppar);
531 sprintf(buf, "%dx%d %s", tmppar->h, tmppar->w, diffnames[tmppar->diff]);
532 *name = dupstr(buf);
533
534 return TRUE;
535 }
536
537 static void free_params(game_params *params)
538 {
539 sfree(params);
540 }
541
542 static void decode_params(game_params *params, char const *string)
543 {
544 params->h = params->w = atoi(string);
545 params->rec = 0;
546 params->diff = DIFF_EASY;
547 while (*string && isdigit((unsigned char)*string)) string++;
548 if (*string == 'x') {
549 string++;
550 params->h = atoi(string);
551 while (*string && isdigit((unsigned char)*string)) string++;
552 }
553 if (*string == 'r') {
554 string++;
555 params->rec = atoi(string);
556 while (*string && isdigit((unsigned char)*string)) string++;
557 }
558 if (*string == 'd') {
559 int i;
560 string++;
561 for (i = 0; i < DIFF_MAX; i++)
562 if (*string == diffchars[i])
563 params->diff = i;
564 if (*string) string++;
565 }
566 }
567
568 static char *encode_params(game_params *params, int full)
569 {
570 char str[80];
571 sprintf(str, "%dx%d", params->w, params->h);
572 if (full)
573 sprintf(str + strlen(str), "r%dd%c", params->rec, diffchars[params->diff]);
574 return dupstr(str);
575 }
576
577 static config_item *game_configure(game_params *params)
578 {
579 config_item *ret;
580 char buf[80];
581
582 ret = snewn(4, config_item);
583
584 ret[0].name = "Width";
585 ret[0].type = C_STRING;
586 sprintf(buf, "%d", params->w);
587 ret[0].sval = dupstr(buf);
588 ret[0].ival = 0;
589
590 ret[1].name = "Height";
591 ret[1].type = C_STRING;
592 sprintf(buf, "%d", params->h);
593 ret[1].sval = dupstr(buf);
594 ret[1].ival = 0;
595
596 ret[2].name = "Difficulty";
597 ret[2].type = C_CHOICES;
598 ret[2].sval = DIFFCONFIG;
599 ret[2].ival = params->diff;
600
601 ret[3].name = NULL;
602 ret[3].type = C_END;
603 ret[3].sval = NULL;
604 ret[3].ival = 0;
605
606 return ret;
607 }
608
609 static game_params *custom_params(config_item *cfg)
610 {
611 game_params *ret = snew(game_params);
612
613 ret->w = atoi(cfg[0].sval);
614 ret->h = atoi(cfg[1].sval);
615 ret->rec = 0;
616 ret->diff = cfg[2].ival;
617
618 return ret;
619 }
620
621 static char *validate_params(game_params *params, int full)
622 {
623 if (params->w < 4 || params->h < 4)
624 return "Width and height must both be at least 4";
625 if (params->rec < 0)
626 return "Recursion depth can't be negative";
627
628 /*
629 * This shouldn't be able to happen at all, since decode_params
630 * and custom_params will never generate anything that isn't
631 * within range.
632 */
633 assert(params->diff >= 0 && params->diff < DIFF_MAX);
634
635 return NULL;
636 }
637
638 /* Returns a newly allocated string describing the current puzzle */
639 static char *state_to_text(const game_state *state)
640 {
641 char *retval;
642 char *description = snewn(SQUARE_COUNT(state) + 1, char);
643 char *dp = description;
644 int empty_count = 0;
645 int i, j;
646
647 FORALL_SQUARES(state, i, j) {
648 if (CLUE_AT(state, i, j) < 0) {
649 if (empty_count > 25) {
650 dp += sprintf(dp, "%c", (int)(empty_count + 'a' - 1));
651 empty_count = 0;
652 }
653 empty_count++;
654 } else {
655 if (empty_count) {
656 dp += sprintf(dp, "%c", (int)(empty_count + 'a' - 1));
657 empty_count = 0;
658 }
659 dp += sprintf(dp, "%c", CLUE2CHAR(CLUE_AT(state, i, j)));
660 }
661 }
662
663 if (empty_count)
664 dp += sprintf(dp, "%c", (empty_count + 'a' - 1));
665
666 retval = dupstr(description);
667 sfree(description);
668
669 return retval;
670 }
671
672 /* We require that the params pass the test in validate_params and that the
673 * description fills the entire game area */
674 static char *validate_desc(game_params *params, char *desc)
675 {
676 int count = 0;
677
678 for (; *desc; ++desc) {
679 if (*desc >= '0' && *desc <= '9') {
680 count++;
681 continue;
682 }
683 if (*desc >= 'a') {
684 count += *desc - 'a' + 1;
685 continue;
686 }
687 return "Unknown character in description";
688 }
689
690 if (count < SQUARE_COUNT(params))
691 return "Description too short for board size";
692 if (count > SQUARE_COUNT(params))
693 return "Description too long for board size";
694
695 return NULL;
696 }
697
698 /* Sums the lengths of the numbers in range [0,n) */
699 /* See equivalent function in solo.c for justification of this. */
700 static int len_0_to_n(int n)
701 {
702 int len = 1; /* Counting 0 as a bit of a special case */
703 int i;
704
705 for (i = 1; i < n; i *= 10) {
706 len += max(n - i, 0);
707 }
708
709 return len;
710 }
711
712 static char *encode_solve_move(const game_state *state)
713 {
714 int len, i, j;
715 char *ret, *p;
716 /* This is going to return a string representing the moves needed to set
717 * every line in a grid to be the same as the ones in 'state'. The exact
718 * length of this string is predictable. */
719
720 len = 1; /* Count the 'S' prefix */
721 /* Numbers in horizontal lines */
722 /* Horizontal lines, x position */
723 len += len_0_to_n(state->w) * (state->h + 1);
724 /* Horizontal lines, y position */
725 len += len_0_to_n(state->h + 1) * (state->w);
726 /* Vertical lines, y position */
727 len += len_0_to_n(state->h) * (state->w + 1);
728 /* Vertical lines, x position */
729 len += len_0_to_n(state->w + 1) * (state->h);
730 /* For each line we also have two letters and a comma */
731 len += 3 * (LINE_COUNT(state));
732
733 ret = snewn(len + 1, char);
734 p = ret;
735
736 p += sprintf(p, "S");
737
738 FORALL_HL(state, i, j) {
739 switch (RIGHTOF_DOT(state, i, j)) {
740 case LINE_YES:
741 p += sprintf(p, "%d,%dhy", i, j);
742 break;
743 case LINE_NO:
744 p += sprintf(p, "%d,%dhn", i, j);
745 break;
746 }
747 }
748
749 FORALL_VL(state, i, j) {
750 switch (BELOW_DOT(state, i, j)) {
751 case LINE_YES:
752 p += sprintf(p, "%d,%dvy", i, j);
753 break;
754 case LINE_NO:
755 p += sprintf(p, "%d,%dvn", i, j);
756 break;
757 }
758 }
759
760 /* No point in doing sums like that if they're going to be wrong */
761 assert(strlen(ret) <= (size_t)len);
762 return ret;
763 }
764
765 static game_ui *new_ui(game_state *state)
766 {
767 return NULL;
768 }
769
770 static void free_ui(game_ui *ui)
771 {
772 }
773
774 static char *encode_ui(game_ui *ui)
775 {
776 return NULL;
777 }
778
779 static void decode_ui(game_ui *ui, char *encoding)
780 {
781 }
782
783 static void game_changed_state(game_ui *ui, game_state *oldstate,
784 game_state *newstate)
785 {
786 }
787
788 #define SIZE(d) ((d) * TILE_SIZE + 2 * BORDER + 1)
789
790 static void game_compute_size(game_params *params, int tilesize,
791 int *x, int *y)
792 {
793 struct { int tilesize; } ads, *ds = &ads;
794 ads.tilesize = tilesize;
795
796 *x = SIZE(params->w);
797 *y = SIZE(params->h);
798 }
799
800 static void game_set_size(drawing *dr, game_drawstate *ds,
801 game_params *params, int tilesize)
802 {
803 ds->tilesize = tilesize;
804 ds->linewidth = max(1,tilesize/16);
805 }
806
807 static float *game_colours(frontend *fe, int *ncolours)
808 {
809 float *ret = snewn(4 * NCOLOURS, float);
810
811 frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
812
813 ret[COL_FOREGROUND * 3 + 0] = 0.0F;
814 ret[COL_FOREGROUND * 3 + 1] = 0.0F;
815 ret[COL_FOREGROUND * 3 + 2] = 0.0F;
816
817 ret[COL_HIGHLIGHT * 3 + 0] = 1.0F;
818 ret[COL_HIGHLIGHT * 3 + 1] = 1.0F;
819 ret[COL_HIGHLIGHT * 3 + 2] = 1.0F;
820
821 ret[COL_MISTAKE * 3 + 0] = 1.0F;
822 ret[COL_MISTAKE * 3 + 1] = 0.0F;
823 ret[COL_MISTAKE * 3 + 2] = 0.0F;
824
825 *ncolours = NCOLOURS;
826 return ret;
827 }
828
829 static game_drawstate *game_new_drawstate(drawing *dr, game_state *state)
830 {
831 struct game_drawstate *ds = snew(struct game_drawstate);
832
833 ds->tilesize = ds->linewidth = 0;
834 ds->started = 0;
835 ds->hl = snewn(HL_COUNT(state), char);
836 ds->vl = snewn(VL_COUNT(state), char);
837 ds->clue_error = snewn(SQUARE_COUNT(state), char);
838 ds->flashing = 0;
839
840 memset(ds->hl, LINE_UNKNOWN, HL_COUNT(state));
841 memset(ds->vl, LINE_UNKNOWN, VL_COUNT(state));
842 memset(ds->clue_error, 0, SQUARE_COUNT(state));
843
844 return ds;
845 }
846
847 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
848 {
849 sfree(ds->clue_error);
850 sfree(ds->hl);
851 sfree(ds->vl);
852 sfree(ds);
853 }
854
855 static int game_timing_state(game_state *state, game_ui *ui)
856 {
857 return TRUE;
858 }
859
860 static float game_anim_length(game_state *oldstate, game_state *newstate,
861 int dir, game_ui *ui)
862 {
863 return 0.0F;
864 }
865
866 static char *game_text_format(game_state *state)
867 {
868 int i, j;
869 int len;
870 char *ret, *rp;
871
872 len = (2 * state->w + 2) * (2 * state->h + 1);
873 rp = ret = snewn(len + 1, char);
874
875 #define DRAW_HL \
876 switch (ABOVE_SQUARE(state, i, j)) { \
877 case LINE_YES: \
878 rp += sprintf(rp, " -"); \
879 break; \
880 case LINE_NO: \
881 rp += sprintf(rp, " x"); \
882 break; \
883 case LINE_UNKNOWN: \
884 rp += sprintf(rp, " "); \
885 break; \
886 default: \
887 assert(!"Illegal line state for HL"); \
888 }
889
890 #define DRAW_VL \
891 switch (LEFTOF_SQUARE(state, i, j)) { \
892 case LINE_YES: \
893 rp += sprintf(rp, "|"); \
894 break; \
895 case LINE_NO: \
896 rp += sprintf(rp, "x"); \
897 break; \
898 case LINE_UNKNOWN: \
899 rp += sprintf(rp, " "); \
900 break; \
901 default: \
902 assert(!"Illegal line state for VL"); \
903 }
904
905 for (j = 0; j < state->h; ++j) {
906 for (i = 0; i < state->w; ++i) {
907 DRAW_HL;
908 }
909 rp += sprintf(rp, " \n");
910 for (i = 0; i < state->w; ++i) {
911 DRAW_VL;
912 rp += sprintf(rp, "%c", CLUE2CHAR(CLUE_AT(state, i, j)));
913 }
914 DRAW_VL;
915 rp += sprintf(rp, "\n");
916 }
917 for (i = 0; i < state->w; ++i) {
918 DRAW_HL;
919 }
920 rp += sprintf(rp, " \n");
921
922 assert(strlen(ret) == len);
923 return ret;
924 }
925
926 /* ----------------------------------------------------------------------
927 * Debug code
928 */
929
930 #ifdef DEBUG_CACHES
931 static void check_caches(const solver_state* sstate)
932 {
933 int i, j;
934 const game_state *state = sstate->state;
935
936 FORALL_DOTS(state, i, j) {
937 #if 0
938 fprintf(stderr, "dot [%d,%d] y: %d %d n: %d %d\n", i, j,
939 dot_order(state, i, j, LINE_YES),
940 sstate->dot_yescount[i + (state->w + 1) * j],
941 dot_order(state, i, j, LINE_NO),
942 sstate->dot_nocount[i + (state->w + 1) * j]);
943 #endif
944
945 assert(dot_order(state, i, j, LINE_YES) ==
946 DOT_YES_COUNT(sstate, i, j));
947 assert(dot_order(state, i, j, LINE_NO) ==
948 DOT_NO_COUNT(sstate, i, j));
949 }
950
951 FORALL_SQUARES(state, i, j) {
952 #if 0
953 fprintf(stderr, "square [%d,%d] y: %d %d n: %d %d\n", i, j,
954 square_order(state, i, j, LINE_YES),
955 sstate->square_yescount[i + state->w * j],
956 square_order(state, i, j, LINE_NO),
957 sstate->square_nocount[i + state->w * j]);
958 #endif
959
960 assert(square_order(state, i, j, LINE_YES) ==
961 SQUARE_YES_COUNT(sstate, i, j));
962 assert(square_order(state, i, j, LINE_NO) ==
963 SQUARE_NO_COUNT(sstate, i, j));
964 }
965 }
966
967 #if 0
968 #define check_caches(s) \
969 do { \
970 fprintf(stderr, "check_caches at line %d\n", __LINE__); \
971 check_caches(s); \
972 } while (0)
973 #endif
974 #endif /* DEBUG_CACHES */
975
976 /* ----------------------------------------------------------------------
977 * Solver utility functions
978 */
979
980 static int set_line_bydot(solver_state *sstate, int x, int y, enum direction d,
981 enum line_state line_new
982 #ifdef SHOW_WORKING
983 , const char *reason
984 #endif
985 )
986 {
987 game_state *state = sstate->state;
988
989 /* This line borders at most two squares in our board. We figure out the
990 * x and y positions of those squares so we can record that their yes or no
991 * counts have been changed */
992 int sq1_x=-1, sq1_y=-1, sq2_x=-1, sq2_y=-1;
993 int otherdot_x=-1, otherdot_y=-1;
994
995 int progress = FALSE;
996
997 #if 0
998 fprintf(stderr, "set_line_bydot [%d,%d], %s, %d\n",
999 x, y, DIR2STR(d), line_new);
1000 #endif
1001
1002 assert(line_new != LINE_UNKNOWN);
1003
1004 check_caches(sstate);
1005
1006 switch (d) {
1007 case LEFT:
1008 assert(x > 0);
1009
1010 if (LEFTOF_DOT(state, x, y) != line_new) {
1011 LV_LEFTOF_DOT(state, x, y) = line_new;
1012
1013 otherdot_x = x-1;
1014 otherdot_y = y;
1015
1016 sq1_x = x-1;
1017 sq1_y = y-1;
1018 sq2_x = x-1;
1019 sq2_y = y;
1020
1021 progress = TRUE;
1022 }
1023 break;
1024 case RIGHT:
1025 assert(x < state->w);
1026 if (RIGHTOF_DOT(state, x, y) != line_new) {
1027 LV_RIGHTOF_DOT(state, x, y) = line_new;
1028
1029 otherdot_x = x+1;
1030 otherdot_y = y;
1031
1032 sq1_x = x;
1033 sq1_y = y-1;
1034 sq2_x = x;
1035 sq2_y = y;
1036
1037 progress = TRUE;
1038 }
1039 break;
1040 case UP:
1041 assert(y > 0);
1042 if (ABOVE_DOT(state, x, y) != line_new) {
1043 LV_ABOVE_DOT(state, x, y) = line_new;
1044
1045 otherdot_x = x;
1046 otherdot_y = y-1;
1047
1048 sq1_x = x-1;
1049 sq1_y = y-1;
1050 sq2_x = x;
1051 sq2_y = y-1;
1052
1053 progress = TRUE;
1054 }
1055 break;
1056 case DOWN:
1057 assert(y < state->h);
1058 if (BELOW_DOT(state, x, y) != line_new) {
1059 LV_BELOW_DOT(state, x, y) = line_new;
1060
1061 otherdot_x = x;
1062 otherdot_y = y+1;
1063
1064 sq1_x = x-1;
1065 sq1_y = y;
1066 sq2_x = x;
1067 sq2_y = y;
1068
1069 progress = TRUE;
1070 }
1071 break;
1072 }
1073
1074 if (!progress)
1075 return progress;
1076
1077 #ifdef SHOW_WORKING
1078 fprintf(stderr, "set line [%d,%d] -> [%d,%d] to %s (%s)\n",
1079 x, y, otherdot_x, otherdot_y, line_new == LINE_YES ? "YES" : "NO",
1080 reason);
1081 #endif
1082
1083 /* Above we updated the cache for the dot that the line in question reaches
1084 * from the dot we've been told about. Here we update that for the dot
1085 * named in our arguments. */
1086 if (line_new == LINE_YES) {
1087 if (sq1_x >= 0 && sq1_y >= 0)
1088 ++SQUARE_YES_COUNT(sstate, sq1_x, sq1_y);
1089 if (sq2_x < state->w && sq2_y < state->h)
1090 ++SQUARE_YES_COUNT(sstate, sq2_x, sq2_y);
1091 ++DOT_YES_COUNT(sstate, x, y);
1092 ++DOT_YES_COUNT(sstate, otherdot_x, otherdot_y);
1093 } else {
1094 if (sq1_x >= 0 && sq1_y >= 0)
1095 ++SQUARE_NO_COUNT(sstate, sq1_x, sq1_y);
1096 if (sq2_x < state->w && sq2_y < state->h)
1097 ++SQUARE_NO_COUNT(sstate, sq2_x, sq2_y);
1098 ++DOT_NO_COUNT(sstate, x, y);
1099 ++DOT_NO_COUNT(sstate, otherdot_x, otherdot_y);
1100 }
1101
1102 check_caches(sstate);
1103 return progress;
1104 }
1105
1106 #ifdef SHOW_WORKING
1107 #define set_line_bydot(a, b, c, d, e) \
1108 set_line_bydot(a, b, c, d, e, __FUNCTION__)
1109 #endif
1110
1111 /*
1112 * Merge two dots due to the existence of an edge between them.
1113 * Updates the dsf tracking equivalence classes, and keeps track of
1114 * the length of path each dot is currently a part of.
1115 * Returns TRUE if the dots were already linked, ie if they are part of a
1116 * closed loop, and false otherwise.
1117 */
1118 static int merge_dots(solver_state *sstate, int x1, int y1, int x2, int y2)
1119 {
1120 int i, j, len;
1121
1122 i = y1 * (sstate->state->w + 1) + x1;
1123 j = y2 * (sstate->state->w + 1) + x2;
1124
1125 i = dsf_canonify(sstate->dotdsf, i);
1126 j = dsf_canonify(sstate->dotdsf, j);
1127
1128 if (i == j) {
1129 return TRUE;
1130 } else {
1131 len = sstate->looplen[i] + sstate->looplen[j];
1132 dsf_merge(sstate->dotdsf, i, j);
1133 i = dsf_canonify(sstate->dotdsf, i);
1134 sstate->looplen[i] = len;
1135 return FALSE;
1136 }
1137 }
1138
1139 /* Seriously, these should be functions */
1140
1141 #define LINEDSF_INDEX(state, x, y, d) \
1142 ((d == UP) ? ((y-1) * (state->w + 1) + x) : \
1143 (d == DOWN) ? ((y) * (state->w + 1) + x) : \
1144 (d == LEFT) ? ((y) * (state->w) + x-1 + VL_COUNT(state)) : \
1145 (d == RIGHT) ? ((y) * (state->w) + x + VL_COUNT(state)) : \
1146 (assert(!"bad direction value"), 0))
1147
1148 static void linedsf_deindex(const game_state *state, int i,
1149 int *px, int *py, enum direction *pd)
1150 {
1151 int i_mod;
1152 if (i < VL_COUNT(state)) {
1153 *(pd) = DOWN;
1154 *(px) = (i) % (state->w+1);
1155 *(py) = (i) / (state->w+1);
1156 } else {
1157 i_mod = i - VL_COUNT(state);
1158 *(pd) = RIGHT;
1159 *(px) = (i_mod) % (state->w);
1160 *(py) = (i_mod) / (state->w);
1161 }
1162 }
1163
1164 /* Merge two lines because the solver has deduced that they must be either
1165 * identical or opposite. Returns TRUE if this is new information, otherwise
1166 * FALSE. */
1167 static int merge_lines(solver_state *sstate,
1168 int x1, int y1, enum direction d1,
1169 int x2, int y2, enum direction d2,
1170 int inverse
1171 #ifdef SHOW_WORKING
1172 , const char *reason
1173 #endif
1174 )
1175 {
1176 int i, j, inv_tmp;
1177
1178 i = LINEDSF_INDEX(sstate->state, x1, y1, d1);
1179 j = LINEDSF_INDEX(sstate->state, x2, y2, d2);
1180
1181 assert(i < LINE_COUNT(sstate->state));
1182 assert(j < LINE_COUNT(sstate->state));
1183
1184 i = edsf_canonify(sstate->hard->linedsf, i, &inv_tmp);
1185 inverse ^= inv_tmp;
1186 j = edsf_canonify(sstate->hard->linedsf, j, &inv_tmp);
1187 inverse ^= inv_tmp;
1188
1189 edsf_merge(sstate->hard->linedsf, i, j, inverse);
1190
1191 #ifdef SHOW_WORKING
1192 if (i != j) {
1193 fprintf(stderr, "%s [%d,%d,%s] [%d,%d,%s] %s(%s)\n",
1194 __FUNCTION__,
1195 x1, y1, DIR2STR(d1),
1196 x2, y2, DIR2STR(d2),
1197 inverse ? "inverse " : "", reason);
1198 }
1199 #endif
1200 return (i != j);
1201 }
1202
1203 #ifdef SHOW_WORKING
1204 #define merge_lines(a, b, c, d, e, f, g, h) \
1205 merge_lines(a, b, c, d, e, f, g, h, __FUNCTION__)
1206 #endif
1207
1208 /* Return 0 if the given lines are not in the same equivalence class, 1 if they
1209 * are known identical, or 2 if they are known opposite */
1210 #if 0
1211 static int lines_related(solver_state *sstate,
1212 int x1, int y1, enum direction d1,
1213 int x2, int y2, enum direction d2)
1214 {
1215 int i, j, inv1, inv2;
1216
1217 i = LINEDSF_INDEX(sstate->state, x1, y1, d1);
1218 j = LINEDSF_INDEX(sstate->state, x2, y2, d2);
1219
1220 i = edsf_canonify(sstate->hard->linedsf, i, &inv1);
1221 j = edsf_canonify(sstate->hard->linedsf, j, &inv2);
1222
1223 if (i == j)
1224 return (inv1 == inv2) ? 1 : 2;
1225 else
1226 return 0;
1227 }
1228 #endif
1229
1230 /* Count the number of lines of a particular type currently going into the
1231 * given dot. Lines going off the edge of the board are assumed fixed no. */
1232 static int dot_order(const game_state* state, int i, int j, char line_type)
1233 {
1234 int n = 0;
1235
1236 if (i > 0) {
1237 if (line_type == LV_LEFTOF_DOT(state, i, j))
1238 ++n;
1239 } else {
1240 if (line_type == LINE_NO)
1241 ++n;
1242 }
1243 if (i < state->w) {
1244 if (line_type == LV_RIGHTOF_DOT(state, i, j))
1245 ++n;
1246 } else {
1247 if (line_type == LINE_NO)
1248 ++n;
1249 }
1250 if (j > 0) {
1251 if (line_type == LV_ABOVE_DOT(state, i, j))
1252 ++n;
1253 } else {
1254 if (line_type == LINE_NO)
1255 ++n;
1256 }
1257 if (j < state->h) {
1258 if (line_type == LV_BELOW_DOT(state, i, j))
1259 ++n;
1260 } else {
1261 if (line_type == LINE_NO)
1262 ++n;
1263 }
1264
1265 return n;
1266 }
1267
1268 /* Count the number of lines of a particular type currently surrounding the
1269 * given square */
1270 static int square_order(const game_state* state, int i, int j, char line_type)
1271 {
1272 int n = 0;
1273
1274 if (ABOVE_SQUARE(state, i, j) == line_type)
1275 ++n;
1276 if (BELOW_SQUARE(state, i, j) == line_type)
1277 ++n;
1278 if (LEFTOF_SQUARE(state, i, j) == line_type)
1279 ++n;
1280 if (RIGHTOF_SQUARE(state, i, j) == line_type)
1281 ++n;
1282
1283 return n;
1284 }
1285
1286 /* Set all lines bordering a dot of type old_type to type new_type
1287 * Return value tells caller whether this function actually did anything */
1288 static int dot_setall(solver_state *sstate, int i, int j,
1289 char old_type, char new_type)
1290 {
1291 int retval = FALSE, r;
1292 game_state *state = sstate->state;
1293
1294 if (old_type == new_type)
1295 return FALSE;
1296
1297 if (i > 0 && LEFTOF_DOT(state, i, j) == old_type) {
1298 r = set_line_bydot(sstate, i, j, LEFT, new_type);
1299 assert(r == TRUE);
1300 retval = TRUE;
1301 }
1302
1303 if (i < state->w && RIGHTOF_DOT(state, i, j) == old_type) {
1304 r = set_line_bydot(sstate, i, j, RIGHT, new_type);
1305 assert(r == TRUE);
1306 retval = TRUE;
1307 }
1308
1309 if (j > 0 && ABOVE_DOT(state, i, j) == old_type) {
1310 r = set_line_bydot(sstate, i, j, UP, new_type);
1311 assert(r == TRUE);
1312 retval = TRUE;
1313 }
1314
1315 if (j < state->h && BELOW_DOT(state, i, j) == old_type) {
1316 r = set_line_bydot(sstate, i, j, DOWN, new_type);
1317 assert(r == TRUE);
1318 retval = TRUE;
1319 }
1320
1321 return retval;
1322 }
1323
1324 /* Set all lines bordering a square of type old_type to type new_type */
1325 static int square_setall(solver_state *sstate, int i, int j,
1326 char old_type, char new_type)
1327 {
1328 int r = FALSE;
1329 game_state *state = sstate->state;
1330
1331 #if 0
1332 fprintf(stderr, "square_setall [%d,%d] from %d to %d\n", i, j,
1333 old_type, new_type);
1334 #endif
1335 if (ABOVE_SQUARE(state, i, j) == old_type) {
1336 r = set_line_bydot(sstate, i, j, RIGHT, new_type);
1337 assert(r == TRUE);
1338 }
1339 if (BELOW_SQUARE(state, i, j) == old_type) {
1340 r = set_line_bydot(sstate, i, j+1, RIGHT, new_type);
1341 assert(r == TRUE);
1342 }
1343 if (LEFTOF_SQUARE(state, i, j) == old_type) {
1344 r = set_line_bydot(sstate, i, j, DOWN, new_type);
1345 assert(r == TRUE);
1346 }
1347 if (RIGHTOF_SQUARE(state, i, j) == old_type) {
1348 r = set_line_bydot(sstate, i+1, j, DOWN, new_type);
1349 assert(r == TRUE);
1350 }
1351
1352 return r;
1353 }
1354
1355 /* ----------------------------------------------------------------------
1356 * Loop generation and clue removal
1357 */
1358
1359 /* We're going to store a list of current candidate squares for lighting.
1360 * Each square gets a 'score', which tells us how adding that square right
1361 * now would affect the length of the solution loop. We're trying to
1362 * maximise that quantity so will bias our random selection of squares to
1363 * light towards those with high scores */
1364 struct square {
1365 int score;
1366 unsigned long random;
1367 int x, y;
1368 };
1369
1370 static int get_square_cmpfn(void *v1, void *v2)
1371 {
1372 struct square *s1 = v1;
1373 struct square *s2 = v2;
1374 int r;
1375
1376 r = s1->x - s2->x;
1377 if (r)
1378 return r;
1379
1380 r = s1->y - s2->y;
1381 if (r)
1382 return r;
1383
1384 return 0;
1385 }
1386
1387 static int square_sort_cmpfn(void *v1, void *v2)
1388 {
1389 struct square *s1 = v1;
1390 struct square *s2 = v2;
1391 int r;
1392
1393 r = s2->score - s1->score;
1394 if (r) {
1395 return r;
1396 }
1397
1398 if (s1->random < s2->random)
1399 return -1;
1400 else if (s1->random > s2->random)
1401 return 1;
1402
1403 /*
1404 * It's _just_ possible that two squares might have been given
1405 * the same random value. In that situation, fall back to
1406 * comparing based on the coordinates. This introduces a tiny
1407 * directional bias, but not a significant one.
1408 */
1409 return get_square_cmpfn(v1, v2);
1410 }
1411
1412 enum { SQUARE_LIT, SQUARE_UNLIT };
1413
1414 #define SQUARE_STATE(i, j) \
1415 ( LEGAL_SQUARE(state, i, j) ? \
1416 LV_SQUARE_STATE(i,j) : \
1417 SQUARE_UNLIT )
1418
1419 #define LV_SQUARE_STATE(i, j) board[SQUARE_INDEX(state, i, j)]
1420
1421 /* Generate a new complete set of clues for the given game_state (respecting
1422 * the dimensions provided by said game_state) */
1423 static void add_full_clues(game_state *state, random_state *rs)
1424 {
1425 char *clues;
1426 char *board;
1427 int i, j, a, b, c;
1428 int board_area = SQUARE_COUNT(state);
1429 int t;
1430
1431 struct square *square, *tmpsquare, *sq;
1432 struct square square_pos;
1433
1434 /* These will contain exactly the same information, sorted into different
1435 * orders */
1436 tree234 *lightable_squares_sorted, *lightable_squares_gettable;
1437
1438 #define SQUARE_REACHABLE(i,j) \
1439 (t = (SQUARE_STATE(i-1, j) == SQUARE_LIT || \
1440 SQUARE_STATE(i+1, j) == SQUARE_LIT || \
1441 SQUARE_STATE(i, j-1) == SQUARE_LIT || \
1442 SQUARE_STATE(i, j+1) == SQUARE_LIT), \
1443 t)
1444
1445 /* One situation in which we may not light a square is if that'll leave one
1446 * square above/below and one left/right of us unlit, separated by a lit
1447 * square diagnonal from us */
1448 #define SQUARE_DIAGONAL_VIOLATION(i, j, h, v) \
1449 (t = (SQUARE_STATE((i)+(h), (j)) == SQUARE_UNLIT && \
1450 SQUARE_STATE((i), (j)+(v)) == SQUARE_UNLIT && \
1451 SQUARE_STATE((i)+(h), (j)+(v)) == SQUARE_LIT), \
1452 t)
1453
1454 /* We also may not light a square if it will form a loop of lit squares
1455 * around some unlit squares, as then the game soln won't have a single
1456 * loop */
1457 #define SQUARE_LOOP_VIOLATION(i, j, lit1, lit2) \
1458 (SQUARE_STATE((i)+1, (j)) == lit1 && \
1459 SQUARE_STATE((i)-1, (j)) == lit1 && \
1460 SQUARE_STATE((i), (j)+1) == lit2 && \
1461 SQUARE_STATE((i), (j)-1) == lit2)
1462
1463 #define CAN_LIGHT_SQUARE(i, j) \
1464 (SQUARE_REACHABLE(i, j) && \
1465 !SQUARE_DIAGONAL_VIOLATION(i, j, -1, -1) && \
1466 !SQUARE_DIAGONAL_VIOLATION(i, j, +1, -1) && \
1467 !SQUARE_DIAGONAL_VIOLATION(i, j, -1, +1) && \
1468 !SQUARE_DIAGONAL_VIOLATION(i, j, +1, +1) && \
1469 !SQUARE_LOOP_VIOLATION(i, j, SQUARE_LIT, SQUARE_UNLIT) && \
1470 !SQUARE_LOOP_VIOLATION(i, j, SQUARE_UNLIT, SQUARE_LIT))
1471
1472 #define IS_LIGHTING_CANDIDATE(i, j) \
1473 (SQUARE_STATE(i, j) == SQUARE_UNLIT && \
1474 CAN_LIGHT_SQUARE(i,j))
1475
1476 /* The 'score' of a square reflects its current desirability for selection
1477 * as the next square to light. We want to encourage moving into uncharted
1478 * areas so we give scores according to how many of the square's neighbours
1479 * are currently unlit. */
1480
1481 /* UNLIT SCORE
1482 * 3 2
1483 * 2 0
1484 * 1 -2
1485 */
1486 #define SQUARE_SCORE(i,j) \
1487 (2*((SQUARE_STATE(i-1, j) == SQUARE_UNLIT) + \
1488 (SQUARE_STATE(i+1, j) == SQUARE_UNLIT) + \
1489 (SQUARE_STATE(i, j-1) == SQUARE_UNLIT) + \
1490 (SQUARE_STATE(i, j+1) == SQUARE_UNLIT)) - 4)
1491
1492 /* When a square gets lit, this defines how far away from that square we
1493 * need to go recomputing scores */
1494 #define SCORE_DISTANCE 1
1495
1496 board = snewn(board_area, char);
1497 clues = state->clues;
1498
1499 /* Make a board */
1500 memset(board, SQUARE_UNLIT, board_area);
1501
1502 /* Seed the board with a single lit square near the middle */
1503 i = state->w / 2;
1504 j = state->h / 2;
1505 if (state->w & 1 && random_bits(rs, 1))
1506 ++i;
1507 if (state->h & 1 && random_bits(rs, 1))
1508 ++j;
1509
1510 LV_SQUARE_STATE(i, j) = SQUARE_LIT;
1511
1512 /* We need a way of favouring squares that will increase our loopiness.
1513 * We do this by maintaining a list of all candidate squares sorted by
1514 * their score and choose randomly from that with appropriate skew.
1515 * In order to avoid consistently biasing towards particular squares, we
1516 * need the sort order _within_ each group of scores to be completely
1517 * random. But it would be abusing the hospitality of the tree234 data
1518 * structure if our comparison function were nondeterministic :-). So with
1519 * each square we associate a random number that does not change during a
1520 * particular run of the generator, and use that as a secondary sort key.
1521 * Yes, this means we will be biased towards particular random squares in
1522 * any one run but that doesn't actually matter. */
1523
1524 lightable_squares_sorted = newtree234(square_sort_cmpfn);
1525 lightable_squares_gettable = newtree234(get_square_cmpfn);
1526 #define ADD_SQUARE(s) \
1527 do { \
1528 sq = add234(lightable_squares_sorted, s); \
1529 assert(sq == s); \
1530 sq = add234(lightable_squares_gettable, s); \
1531 assert(sq == s); \
1532 } while (0)
1533
1534 #define REMOVE_SQUARE(s) \
1535 do { \
1536 sq = del234(lightable_squares_sorted, s); \
1537 assert(sq); \
1538 sq = del234(lightable_squares_gettable, s); \
1539 assert(sq); \
1540 } while (0)
1541
1542 #define HANDLE_DIR(a, b) \
1543 square = snew(struct square); \
1544 square->x = (i)+(a); \
1545 square->y = (j)+(b); \
1546 square->score = 2; \
1547 square->random = random_bits(rs, 31); \
1548 ADD_SQUARE(square);
1549 HANDLE_DIR(-1, 0);
1550 HANDLE_DIR( 1, 0);
1551 HANDLE_DIR( 0,-1);
1552 HANDLE_DIR( 0, 1);
1553 #undef HANDLE_DIR
1554
1555 /* Light squares one at a time until the board is interesting enough */
1556 while (TRUE)
1557 {
1558 /* We have count234(lightable_squares) possibilities, and in
1559 * lightable_squares_sorted they are sorted with the most desirable
1560 * first. */
1561 c = count234(lightable_squares_sorted);
1562 if (c == 0)
1563 break;
1564 assert(c == count234(lightable_squares_gettable));
1565
1566 /* Check that the best square available is any good */
1567 square = (struct square *)index234(lightable_squares_sorted, 0);
1568 assert(square);
1569
1570 /*
1571 * We never want to _decrease_ the loop's perimeter. Making
1572 * moves that leave the perimeter the same is occasionally
1573 * useful: if it were _never_ done then the user would be
1574 * able to deduce illicitly that any degree-zero vertex was
1575 * on the outside of the loop. So we do it sometimes but
1576 * not always.
1577 */
1578 if (square->score < 0 || (square->score == 0 &&
1579 random_upto(rs, 2) == 0)) {
1580 break;
1581 }
1582
1583 assert(square->score == SQUARE_SCORE(square->x, square->y));
1584 assert(SQUARE_STATE(square->x, square->y) == SQUARE_UNLIT);
1585 assert(square->x >= 0 && square->x < state->w);
1586 assert(square->y >= 0 && square->y < state->h);
1587
1588 /* Update data structures */
1589 LV_SQUARE_STATE(square->x, square->y) = SQUARE_LIT;
1590 REMOVE_SQUARE(square);
1591
1592 /* We might have changed the score of any squares up to 2 units away in
1593 * any direction */
1594 for (b = -SCORE_DISTANCE; b <= SCORE_DISTANCE; b++) {
1595 for (a = -SCORE_DISTANCE; a <= SCORE_DISTANCE; a++) {
1596 if (!a && !b)
1597 continue;
1598 square_pos.x = square->x + a;
1599 square_pos.y = square->y + b;
1600 if (square_pos.x < 0 || square_pos.x >= state->w ||
1601 square_pos.y < 0 || square_pos.y >= state->h) {
1602 continue;
1603 }
1604 tmpsquare = find234(lightable_squares_gettable, &square_pos,
1605 NULL);
1606 if (tmpsquare) {
1607 assert(tmpsquare->x == square_pos.x);
1608 assert(tmpsquare->y == square_pos.y);
1609 assert(SQUARE_STATE(tmpsquare->x, tmpsquare->y) ==
1610 SQUARE_UNLIT);
1611 REMOVE_SQUARE(tmpsquare);
1612 } else {
1613 tmpsquare = snew(struct square);
1614 tmpsquare->x = square_pos.x;
1615 tmpsquare->y = square_pos.y;
1616 tmpsquare->random = random_bits(rs, 31);
1617 }
1618 tmpsquare->score = SQUARE_SCORE(tmpsquare->x, tmpsquare->y);
1619
1620 if (IS_LIGHTING_CANDIDATE(tmpsquare->x, tmpsquare->y)) {
1621 ADD_SQUARE(tmpsquare);
1622 } else {
1623 sfree(tmpsquare);
1624 }
1625 }
1626 }
1627 sfree(square);
1628 }
1629
1630 /* Clean up */
1631 while ((square = delpos234(lightable_squares_gettable, 0)) != NULL)
1632 sfree(square);
1633 freetree234(lightable_squares_gettable);
1634 freetree234(lightable_squares_sorted);
1635
1636 /* Copy out all the clues */
1637 FORALL_SQUARES(state, i, j) {
1638 c = SQUARE_STATE(i, j);
1639 LV_CLUE_AT(state, i, j) = 0;
1640 if (SQUARE_STATE(i-1, j) != c) ++LV_CLUE_AT(state, i, j);
1641 if (SQUARE_STATE(i+1, j) != c) ++LV_CLUE_AT(state, i, j);
1642 if (SQUARE_STATE(i, j-1) != c) ++LV_CLUE_AT(state, i, j);
1643 if (SQUARE_STATE(i, j+1) != c) ++LV_CLUE_AT(state, i, j);
1644 }
1645
1646 sfree(board);
1647 }
1648
1649 static int game_has_unique_soln(const game_state *state, enum diff diff)
1650 {
1651 int ret;
1652 solver_state *sstate_new;
1653 solver_state *sstate = new_solver_state((game_state *)state, diff);
1654
1655 sstate_new = solve_game_rec(sstate, diff);
1656
1657 assert(sstate_new->solver_status != SOLVER_MISTAKE);
1658 ret = (sstate_new->solver_status == SOLVER_SOLVED);
1659
1660 free_solver_state(sstate_new);
1661 free_solver_state(sstate);
1662
1663 return ret;
1664 }
1665
1666 /* Remove clues one at a time at random. */
1667 static game_state *remove_clues(game_state *state, random_state *rs,
1668 enum diff diff)
1669 {
1670 int *square_list, squares;
1671 game_state *ret = dup_game(state), *saved_ret;
1672 int n;
1673 #ifdef SHOW_WORKING
1674 char *desc;
1675 #endif
1676
1677 /* We need to remove some clues. We'll do this by forming a list of all
1678 * available clues, shuffling it, then going along one at a
1679 * time clearing each clue in turn for which doing so doesn't render the
1680 * board unsolvable. */
1681 squares = state->w * state->h;
1682 square_list = snewn(squares, int);
1683 for (n = 0; n < squares; ++n) {
1684 square_list[n] = n;
1685 }
1686
1687 shuffle(square_list, squares, sizeof(int), rs);
1688
1689 for (n = 0; n < squares; ++n) {
1690 saved_ret = dup_game(ret);
1691 LV_CLUE_AT(ret, square_list[n] % state->w,
1692 square_list[n] / state->w) = -1;
1693
1694 #ifdef SHOW_WORKING
1695 desc = state_to_text(ret);
1696 fprintf(stderr, "%dx%d:%s\n", state->w, state->h, desc);
1697 sfree(desc);
1698 #endif
1699
1700 if (game_has_unique_soln(ret, diff)) {
1701 free_game(saved_ret);
1702 } else {
1703 free_game(ret);
1704 ret = saved_ret;
1705 }
1706 }
1707 sfree(square_list);
1708
1709 return ret;
1710 }
1711
1712 static char *new_game_desc(game_params *params, random_state *rs,
1713 char **aux, int interactive)
1714 {
1715 /* solution and description both use run-length encoding in obvious ways */
1716 char *retval;
1717 game_state *state = snew(game_state), *state_new;
1718
1719 state->h = params->h;
1720 state->w = params->w;
1721
1722 state->clues = snewn(SQUARE_COUNT(params), char);
1723 state->hl = snewn(HL_COUNT(params), char);
1724 state->vl = snewn(VL_COUNT(params), char);
1725
1726 newboard_please:
1727 memset(state->hl, LINE_UNKNOWN, HL_COUNT(params));
1728 memset(state->vl, LINE_UNKNOWN, VL_COUNT(params));
1729
1730 state->solved = state->cheated = FALSE;
1731 state->recursion_depth = params->rec;
1732
1733 /* Get a new random solvable board with all its clues filled in. Yes, this
1734 * can loop for ever if the params are suitably unfavourable, but
1735 * preventing games smaller than 4x4 seems to stop this happening */
1736
1737 do {
1738 add_full_clues(state, rs);
1739 } while (!game_has_unique_soln(state, params->diff));
1740
1741 state_new = remove_clues(state, rs, params->diff);
1742 free_game(state);
1743 state = state_new;
1744
1745 if (params->diff > 0 && game_has_unique_soln(state, params->diff-1)) {
1746 fprintf(stderr, "Rejecting board, it is too easy\n");
1747 goto newboard_please;
1748 }
1749
1750 retval = state_to_text(state);
1751
1752 free_game(state);
1753
1754 assert(!validate_desc(params, retval));
1755
1756 return retval;
1757 }
1758
1759 static game_state *new_game(midend *me, game_params *params, char *desc)
1760 {
1761 int i,j;
1762 game_state *state = snew(game_state);
1763 int empties_to_make = 0;
1764 int n;
1765 const char *dp = desc;
1766
1767 state->recursion_depth = 0; /* XXX pending removal, probably */
1768
1769 state->h = params->h;
1770 state->w = params->w;
1771
1772 state->clues = snewn(SQUARE_COUNT(params), char);
1773 state->hl = snewn(HL_COUNT(params), char);
1774 state->vl = snewn(VL_COUNT(params), char);
1775
1776 state->solved = state->cheated = FALSE;
1777
1778 FORALL_SQUARES(params, i, j) {
1779 if (empties_to_make) {
1780 empties_to_make--;
1781 LV_CLUE_AT(state, i, j) = -1;
1782 continue;
1783 }
1784
1785 assert(*dp);
1786 n = *dp - '0';
1787 if (n >= 0 && n < 10) {
1788 LV_CLUE_AT(state, i, j) = n;
1789 } else {
1790 n = *dp - 'a' + 1;
1791 assert(n > 0);
1792 LV_CLUE_AT(state, i, j) = -1;
1793 empties_to_make = n - 1;
1794 }
1795 ++dp;
1796 }
1797
1798 memset(state->hl, LINE_UNKNOWN, HL_COUNT(params));
1799 memset(state->vl, LINE_UNKNOWN, VL_COUNT(params));
1800
1801 return state;
1802 }
1803
1804 enum { LOOP_NONE=0, LOOP_SOLN, LOOP_NOT_SOLN };
1805
1806 /* ----------------------------------------------------------------------
1807 * Solver logic
1808 *
1809 * Our solver modes operate as follows. Each mode also uses the modes above it.
1810 *
1811 * Easy Mode
1812 * Just implement the rules of the game.
1813 *
1814 * Normal Mode
1815 * For each pair of lines through each dot we store a bit for whether
1816 * at least one of them is on and whether at most one is on. (If we know
1817 * both or neither is on that's already stored more directly.) That's six
1818 * bits per dot. Bit number n represents the lines shown in dline_desc.
1819 *
1820 * Advanced Mode
1821 * Use edsf data structure to make equivalence classes of lines that are
1822 * known identical to or opposite to one another.
1823 */
1824
1825 /* The order the following are defined in is very important, see below.
1826 * The last two fields may seem non-obvious: they specify that when talking
1827 * about a square the dx and dy offsets should be added to the square coords to
1828 * get to the right dot. Where dx and dy are -1 this means that the dline
1829 * doesn't make sense for a square. */
1830 /* XXX can this be done with a struct instead? */
1831 #define DLINES \
1832 DLINE(DLINE_UD, UP, DOWN, -1, -1) \
1833 DLINE(DLINE_LR, LEFT, RIGHT, -1, -1) \
1834 DLINE(DLINE_UR, UP, RIGHT, 0, 1) \
1835 DLINE(DLINE_DL, DOWN, LEFT, 1, 0) \
1836 DLINE(DLINE_UL, UP, LEFT, 1, 1) \
1837 DLINE(DLINE_DR, DOWN, RIGHT, 0, 0)
1838
1839 #define OPP_DLINE(dline_desc) ((dline_desc) ^ 1)
1840
1841 enum dline_desc {
1842 #define DLINE(desc, dir1, dir2, dx, dy) \
1843 desc,
1844 DLINES
1845 #undef DLINE
1846 };
1847
1848 struct dline {
1849 enum dline_desc desc;
1850 enum direction dir1, dir2;
1851 int dx, dy;
1852 };
1853
1854 const static struct dline dlines[] = {
1855 #define DLINE(desc, dir1, dir2, dx, dy) \
1856 { desc, dir1, dir2, dx, dy },
1857 DLINES
1858 #undef DLINE
1859 };
1860
1861 #define FORALL_DOT_DLINES(dl_iter) \
1862 for (dl_iter = 0; dl_iter < lenof(dlines); ++dl_iter)
1863
1864 #define FORALL_SQUARE_DLINES(dl_iter) \
1865 for (dl_iter = 2; dl_iter < lenof(dlines); ++dl_iter)
1866
1867 #define DL2STR(d) \
1868 ((d==DLINE_UD) ? "DLINE_UD": \
1869 (d==DLINE_LR) ? "DLINE_LR": \
1870 (d==DLINE_UR) ? "DLINE_UR": \
1871 (d==DLINE_DL) ? "DLINE_DL": \
1872 (d==DLINE_UL) ? "DLINE_UL": \
1873 (d==DLINE_DR) ? "DLINE_DR": \
1874 "oops")
1875
1876 static const struct dline *get_dline(enum dline_desc desc)
1877 {
1878 return &dlines[desc];
1879 }
1880
1881 /* This will fail an assertion if the directions handed to it are the same, as
1882 * no dline corresponds to that */
1883 static enum dline_desc dline_desc_from_dirs(enum direction dir1,
1884 enum direction dir2)
1885 {
1886 const struct dline *dl;
1887 int i;
1888
1889 assert (dir1 != dir2);
1890
1891 for (i = 0; i < lenof(dlines); ++i) {
1892 dl = &dlines[i];
1893 if ((dir1 == dl->dir1 && dir2 == dl->dir2) ||
1894 (dir1 == dl->dir2 && dir2 == dl->dir1)) {
1895 return dl->desc;
1896 }
1897 }
1898
1899 assert(!"dline not found");
1900 return DLINE_UD; /* placate compiler */
1901 }
1902
1903 /* The following functions allow you to get or set info about the selected
1904 * dline corresponding to the dot or square at [i,j]. You'll get an assertion
1905 * failure if you talk about a dline that doesn't exist, ie if you ask about
1906 * non-touching lines around a square. */
1907 static inline int get_dot_dline(const game_state *state, const char *dline_array,
1908 int i, int j, enum dline_desc desc)
1909 {
1910 /* fprintf(stderr, "get_dot_dline %p [%d,%d] %s\n", dline_array, i, j, DL2STR(desc)); */
1911 return BIT_SET(dline_array[i + (state->w + 1) * j], desc);
1912 }
1913
1914 static int set_dot_dline(game_state *state, char *dline_array,
1915 int i, int j, enum dline_desc desc
1916 #ifdef SHOW_WORKING
1917 , const char *reason
1918 #endif
1919 )
1920 {
1921 int ret;
1922 ret = SET_BIT(dline_array[i + (state->w + 1) * j], desc);
1923
1924 #ifdef SHOW_WORKING
1925 if (ret)
1926 fprintf(stderr, "set_dot_dline %p [%d,%d] %s (%s)\n", dline_array, i, j, DL2STR(desc), reason);
1927 #endif
1928 return ret;
1929 }
1930
1931 static int get_square_dline(game_state *state, char *dline_array,
1932 int i, int j, enum dline_desc desc)
1933 {
1934 const struct dline *dl = get_dline(desc);
1935 assert(dl->dx != -1 && dl->dy != -1);
1936 /* fprintf(stderr, "get_square_dline %p [%d,%d] %s\n", dline_array, i, j, DL2STR(desc)); */
1937 return BIT_SET(dline_array[(i+dl->dx) + (state->w + 1) * (j+dl->dy)],
1938 desc);
1939 }
1940
1941 static int set_square_dline(game_state *state, char *dline_array,
1942 int i, int j, enum dline_desc desc
1943 #ifdef SHOW_WORKING
1944 , const char *reason
1945 #endif
1946 )
1947 {
1948 const struct dline *dl = get_dline(desc);
1949 int ret;
1950 assert(dl->dx != -1 && dl->dy != -1);
1951 ret = SET_BIT(dline_array[(i+dl->dx) + (state->w + 1) * (j+dl->dy)], desc);
1952 #ifdef SHOW_WORKING
1953 if (ret)
1954 fprintf(stderr, "set_square_dline %p [%d,%d] %s (%s)\n", dline_array, i, j, DL2STR(desc), reason);
1955 #endif
1956 return ret;
1957 }
1958
1959 #ifdef SHOW_WORKING
1960 #define set_dot_dline(a, b, c, d, e) \
1961 set_dot_dline(a, b, c, d, e, __FUNCTION__)
1962 #define set_square_dline(a, b, c, d, e) \
1963 set_square_dline(a, b, c, d, e, __FUNCTION__)
1964 #endif
1965
1966 static int set_dot_opp_dline(game_state *state, char *dline_array,
1967 int i, int j, enum dline_desc desc)
1968 {
1969 return set_dot_dline(state, dline_array, i, j, OPP_DLINE(desc));
1970 }
1971
1972 static int set_square_opp_dline(game_state *state, char *dline_array,
1973 int i, int j, enum dline_desc desc)
1974 {
1975 return set_square_dline(state, dline_array, i, j, OPP_DLINE(desc));
1976 }
1977
1978 /* Find out if both the lines in the given dline are UNKNOWN */
1979 static int dline_both_unknown(const game_state *state, int i, int j,
1980 enum dline_desc desc)
1981 {
1982 const struct dline *dl = get_dline(desc);
1983 return
1984 (get_line_status_from_point(state, i, j, dl->dir1) == LINE_UNKNOWN) &&
1985 (get_line_status_from_point(state, i, j, dl->dir2) == LINE_UNKNOWN);
1986 }
1987
1988 #define SQUARE_DLINES \
1989 HANDLE_DLINE(DLINE_UL, RIGHTOF_SQUARE, BELOW_SQUARE, 1, 1); \
1990 HANDLE_DLINE(DLINE_UR, LEFTOF_SQUARE, BELOW_SQUARE, 0, 1); \
1991 HANDLE_DLINE(DLINE_DL, RIGHTOF_SQUARE, ABOVE_SQUARE, 1, 0); \
1992 HANDLE_DLINE(DLINE_DR, LEFTOF_SQUARE, ABOVE_SQUARE, 0, 0);
1993
1994 #define DOT_DLINES \
1995 HANDLE_DLINE(DLINE_UD, ABOVE_DOT, BELOW_DOT); \
1996 HANDLE_DLINE(DLINE_LR, LEFTOF_DOT, RIGHTOF_DOT); \
1997 HANDLE_DLINE(DLINE_UL, ABOVE_DOT, LEFTOF_DOT); \
1998 HANDLE_DLINE(DLINE_UR, ABOVE_DOT, RIGHTOF_DOT); \
1999 HANDLE_DLINE(DLINE_DL, BELOW_DOT, LEFTOF_DOT); \
2000 HANDLE_DLINE(DLINE_DR, BELOW_DOT, RIGHTOF_DOT);
2001
2002 static void array_setall(char *array, char from, char to, int len)
2003 {
2004 char *p = array, *p_old = p;
2005 int len_remaining = len;
2006
2007 while ((p = memchr(p, from, len_remaining))) {
2008 *p = to;
2009 len_remaining -= p - p_old;
2010 p_old = p;
2011 }
2012 }
2013
2014
2015
2016 static int get_line_status_from_point(const game_state *state,
2017 int x, int y, enum direction d)
2018 {
2019 switch (d) {
2020 case LEFT:
2021 return LEFTOF_DOT(state, x, y);
2022 case RIGHT:
2023 return RIGHTOF_DOT(state, x, y);
2024 case UP:
2025 return ABOVE_DOT(state, x, y);
2026 case DOWN:
2027 return BELOW_DOT(state, x, y);
2028 }
2029
2030 return 0;
2031 }
2032
2033 /* First and second args are coord offset from top left of square to one end
2034 * of line in question, third and fourth args are the direction from the first
2035 * end of the line to the second. Fifth arg is the direction of the line from
2036 * the coord offset position.
2037 * How confusing.
2038 */
2039 #define SQUARE_LINES \
2040 SQUARE_LINE( 0, 0, RIGHT, RIGHTOF_DOT, UP); \
2041 SQUARE_LINE( 0, +1, RIGHT, RIGHTOF_DOT, DOWN); \
2042 SQUARE_LINE( 0, 0, DOWN, BELOW_DOT, LEFT); \
2043 SQUARE_LINE(+1, 0, DOWN, BELOW_DOT, RIGHT);
2044
2045 /* Set pairs of lines around this square which are known to be identical to
2046 * the given line_state */
2047 static int square_setall_identical(solver_state *sstate, int x, int y,
2048 enum line_state line_new)
2049 {
2050 /* can[dir] contains the canonical line associated with the line in
2051 * direction dir from the square in question. Similarly inv[dir] is
2052 * whether or not the line in question is inverse to its canonical
2053 * element. */
2054 int can[4], inv[4], i, j;
2055 int retval = FALSE;
2056
2057 i = 0;
2058
2059 #if 0
2060 fprintf(stderr, "Setting all identical unknown lines around square "
2061 "[%d,%d] to %d:\n", x, y, line_new);
2062 #endif
2063
2064 #define SQUARE_LINE(dx, dy, linedir, dir_dot, sqdir) \
2065 can[sqdir] = \
2066 edsf_canonify(sstate->hard->linedsf, \
2067 LINEDSF_INDEX(sstate->state, x+dx, y+dy, linedir), \
2068 &inv[sqdir]);
2069
2070 SQUARE_LINES;
2071
2072 #undef SQUARE_LINE
2073
2074 for (j = 0; j < 4; ++j) {
2075 for (i = 0; i < 4; ++i) {
2076 if (i == j)
2077 continue;
2078
2079 if (can[i] == can[j] && inv[i] == inv[j]) {
2080
2081 /* Lines in directions i and j are identical.
2082 * Only do j now, we'll do i when the loop causes us to
2083 * consider {i,j} in the opposite order. */
2084 #define SQUARE_LINE(dx, dy, dir, c, sqdir) \
2085 if (j == sqdir) { \
2086 retval = set_line_bydot(sstate, x+dx, y+dy, dir, line_new); \
2087 if (retval) { \
2088 break; \
2089 } \
2090 }
2091
2092 SQUARE_LINES;
2093
2094 #undef SQUARE_LINE
2095 }
2096 }
2097 }
2098
2099 return retval;
2100 }
2101
2102 #if 0
2103 /* Set all identical lines passing through the current dot to the chosen line
2104 * state. (implicitly this only looks at UNKNOWN lines) */
2105 static int dot_setall_identical(solver_state *sstate, int x, int y,
2106 enum line_state line_new)
2107 {
2108 /* The implementation of this is a little naughty but I can't see how to do
2109 * it elegantly any other way */
2110 int can[4], inv[4], i, j;
2111 enum direction d;
2112 int retval = FALSE;
2113
2114 for (d = 0; d < 4; ++d) {
2115 can[d] = edsf_canonify(sstate->hard->linedsf,
2116 LINEDSF_INDEX(sstate->state, x, y, d),
2117 inv+d);
2118 }
2119
2120 for (j = 0; j < 4; ++j) {
2121 next_j:
2122 for (i = 0; i < j; ++i) {
2123 if (can[i] == can[j] && inv[i] == inv[j]) {
2124 /* Lines in directions i and j are identical */
2125 if (get_line_status_from_point(sstate->state, x, y, j) ==
2126 LINE_UNKNOWN) {
2127 set_line_bydot(sstate->state, x, y, j,
2128 line_new);
2129 retval = TRUE;
2130 goto next_j;
2131 }
2132 }
2133
2134 }
2135 }
2136
2137 return retval;
2138 }
2139 #endif
2140
2141 static int square_setboth_in_dline(solver_state *sstate, enum dline_desc dd,
2142 int i, int j, enum line_state line_new)
2143 {
2144 int retval = FALSE;
2145 const struct dline *dl = get_dline(dd);
2146
2147 #if 0
2148 fprintf(stderr, "square_setboth_in_dline %s [%d,%d] to %d\n",
2149 DL2STR(dd), i, j, line_new);
2150 #endif
2151
2152 assert(dl->dx != -1 && dl->dy != -1);
2153
2154 retval |=
2155 set_line_bydot(sstate, i+dl->dx, j+dl->dy, dl->dir1, line_new);
2156 retval |=
2157 set_line_bydot(sstate, i+dl->dx, j+dl->dy, dl->dir2, line_new);
2158
2159 return retval;
2160 }
2161
2162 /* Call this function to register that the two unknown lines going into the dot
2163 * [x,y] are identical or opposite (depending on the value of 'inverse'). This
2164 * function will cause an assertion failure if anything other than exactly two
2165 * lines into the dot are unknown.
2166 * As usual returns TRUE if any progress was made, otherwise FALSE. */
2167 static int dot_relate_2_unknowns(solver_state *sstate, int x, int y, int inverse)
2168 {
2169 enum direction d1=DOWN, d2=DOWN; /* Just to keep compiler quiet */
2170 int dirs_set = 0;
2171
2172 #define TRY_DIR(d) \
2173 if (get_line_status_from_point(sstate->state, x, y, d) == \
2174 LINE_UNKNOWN) { \
2175 if (dirs_set == 0) \
2176 d1 = d; \
2177 else { \
2178 assert(dirs_set == 1); \
2179 d2 = d; \
2180 } \
2181 dirs_set++; \
2182 } while (0)
2183
2184 TRY_DIR(UP);
2185 TRY_DIR(DOWN);
2186 TRY_DIR(LEFT);
2187 TRY_DIR(RIGHT);
2188 #undef TRY_DIR
2189
2190 assert(dirs_set == 2);
2191 assert(d1 != d2);
2192
2193 #if 0
2194 fprintf(stderr, "Lines in direction %s and %s from dot [%d,%d] are %s\n",
2195 DIR2STR(d1), DIR2STR(d2), x, y, inverse?"opposite":"the same");
2196 #endif
2197
2198 return merge_lines(sstate, x, y, d1, x, y, d2, inverse);
2199 }
2200
2201 /* Very similar to dot_relate_2_unknowns. */
2202 static int square_relate_2_unknowns(solver_state *sstate, int x, int y, int inverse)
2203 {
2204 enum direction d1=DOWN, d2=DOWN;
2205 int x1=-1, y1=-1, x2=-1, y2=-1;
2206 int dirs_set = 0;
2207
2208 #if 0
2209 fprintf(stderr, "2 unknowns around square [%d,%d] are %s\n",
2210 x, y, inverse?"opposite":"the same");
2211 #endif
2212
2213 #define TRY_DIR(i, j, d, dir_sq) \
2214 do { \
2215 if (dir_sq(sstate->state, x, y) == LINE_UNKNOWN) { \
2216 if (dirs_set == 0) { \
2217 d1 = d; x1 = i; y1 = j; \
2218 } else { \
2219 assert(dirs_set == 1); \
2220 d2 = d; x2 = i; y2 = j; \
2221 } \
2222 dirs_set++; \
2223 } \
2224 } while (0)
2225
2226 TRY_DIR(x, y, RIGHT, ABOVE_SQUARE);
2227 TRY_DIR(x, y, DOWN, LEFTOF_SQUARE);
2228 TRY_DIR(x+1, y, DOWN, RIGHTOF_SQUARE);
2229 TRY_DIR(x, y+1, RIGHT, BELOW_SQUARE);
2230 #undef TRY_DIR
2231
2232 assert(dirs_set == 2);
2233
2234 #if 0
2235 fprintf(stderr, "Line in direction %s from dot [%d,%d] and line in direction %s from dot [%2d,%2d] are %s\n",
2236 DIR2STR(d1), x1, y1, DIR2STR(d2), x2, y2, inverse?"opposite":"the same");
2237 #endif
2238
2239 return merge_lines(sstate, x1, y1, d1, x2, y2, d2, inverse);
2240 }
2241
2242 /* Figure out if any dlines can be 'collapsed' (and do so if they can). This
2243 * can happen if one of the lines is known and due to the dline status this
2244 * tells us state of the other, or if there's an interaction with the linedsf
2245 * (ie if atmostone is set for a dline and the lines are known identical they
2246 * must both be LINE_NO, etc). XXX at the moment only the former is
2247 * implemented, and indeed the latter should be implemented in the hard mode
2248 * solver only.
2249 */
2250 static int dot_collapse_dlines(solver_state *sstate, int i, int j)
2251 {
2252 int progress = FALSE;
2253 enum direction dir1, dir2;
2254 int dir1st;
2255 int dlset;
2256 game_state *state = sstate->state;
2257 enum dline_desc dd;
2258
2259 for (dir1 = 0; dir1 < 4; dir1++) {
2260 dir1st = get_line_status_from_point(state, i, j, dir1);
2261 if (dir1st == LINE_UNKNOWN)
2262 continue;
2263 /* dir2 iterates over the whole range rather than starting at dir1+1
2264 * because test below is asymmetric */
2265 for (dir2 = 0; dir2 < 4; dir2++) {
2266 if (dir1 == dir2)
2267 continue;
2268
2269 if ((i == 0 && (dir1 == LEFT || dir2 == LEFT)) ||
2270 (j == 0 && (dir1 == UP || dir2 == UP)) ||
2271 (i == state->w && (dir1 == RIGHT || dir2 == RIGHT)) ||
2272 (j == state->h && (dir1 == DOWN || dir2 == DOWN))) {
2273 continue;
2274 }
2275
2276 #if 0
2277 fprintf(stderr, "dot_collapse_dlines [%d,%d], %s %s\n", i, j,
2278 DIR2STR(dir1), DIR2STR(dir2));
2279 #endif
2280
2281 if (get_line_status_from_point(state, i, j, dir2) ==
2282 LINE_UNKNOWN) {
2283 dd = dline_desc_from_dirs(dir1, dir2);
2284
2285 dlset = get_dot_dline(state, sstate->normal->dot_atmostone, i, j, dd);
2286 if (dlset && dir1st == LINE_YES) {
2287 /* fprintf(stderr, "setting %s to NO\n", DIR2STR(dir2)); */
2288 progress |=
2289 set_line_bydot(sstate, i, j, dir2, LINE_NO);
2290 }
2291
2292 dlset = get_dot_dline(state, sstate->normal->dot_atleastone, i, j, dd);
2293 if (dlset && dir1st == LINE_NO) {
2294 /* fprintf(stderr, "setting %s to YES\n", DIR2STR(dir2)); */
2295 progress |=
2296 set_line_bydot(sstate, i, j, dir2, LINE_YES);
2297 }
2298 }
2299 }
2300 }
2301
2302 return progress;
2303 }
2304
2305 /*
2306 * These are the main solver functions.
2307 *
2308 * Their return values are diff values corresponding to the lowest mode solver
2309 * that would notice the work that they have done. For example if the normal
2310 * mode solver adds actual lines or crosses, it will return DIFF_EASY as the
2311 * easy mode solver might be able to make progress using that. It doesn't make
2312 * sense for one of them to return a diff value higher than that of the
2313 * function itself.
2314 *
2315 * Each function returns the lowest value it can, as early as possible, in
2316 * order to try and pass as much work as possible back to the lower level
2317 * solvers which progress more quickly.
2318 */
2319
2320 /* PROPOSED NEW DESIGN:
2321 * We have a work queue consisting of 'events' notifying us that something has
2322 * happened that a particular solver mode might be interested in. For example
2323 * the hard mode solver might do something that helps the normal mode solver at
2324 * dot [x,y] in which case it will enqueue an event recording this fact. Then
2325 * we pull events off the work queue, and hand each in turn to the solver that
2326 * is interested in them. If a solver reports that it failed we pass the same
2327 * event on to progressively more advanced solvers and the loop detector. Once
2328 * we've exhausted an event, or it has helped us progress, we drop it and
2329 * continue to the next one. The events are sorted first in order of solver
2330 * complexity (easy first) then order of insertion (oldest first).
2331 * Once we run out of events we loop over each permitted solver in turn
2332 * (easiest first) until either a deduction is made (and an event therefore
2333 * emerges) or no further deductions can be made (in which case we've failed).
2334 *
2335 * QUESTIONS:
2336 * * How do we 'loop over' a solver when both dots and squares are concerned.
2337 * Answer: first all squares then all dots.
2338 */
2339
2340 static int easy_mode_deductions(solver_state *sstate)
2341 {
2342 int i, j, h, w, current_yes, current_no;
2343 game_state *state;
2344 enum diff diff = DIFF_MAX;
2345
2346 state = sstate->state;
2347 h = state->h;
2348 w = state->w;
2349
2350 /* Per-square deductions */
2351 FORALL_SQUARES(state, i, j) {
2352 if (sstate->square_solved[SQUARE_INDEX(state, i, j)])
2353 continue;
2354
2355 current_yes = SQUARE_YES_COUNT(sstate, i, j);
2356 current_no = SQUARE_NO_COUNT(sstate, i, j);
2357
2358 if (current_yes + current_no == 4) {
2359 sstate->square_solved[SQUARE_INDEX(state, i, j)] = TRUE;
2360 /* diff = min(diff, DIFF_EASY); */
2361 continue;
2362 }
2363
2364 if (CLUE_AT(state, i, j) < 0)
2365 continue;
2366
2367 if (CLUE_AT(state, i, j) < current_yes) {
2368 #if 0
2369 fprintf(stderr, "detected error [%d,%d] in %s at line %d\n", i, j, __FUNCTION__, __LINE__);
2370 #endif
2371 sstate->solver_status = SOLVER_MISTAKE;
2372 return DIFF_EASY;
2373 }
2374 if (CLUE_AT(state, i, j) == current_yes) {
2375 if (square_setall(sstate, i, j, LINE_UNKNOWN, LINE_NO))
2376 diff = min(diff, DIFF_EASY);
2377 sstate->square_solved[SQUARE_INDEX(state, i, j)] = TRUE;
2378 continue;
2379 }
2380
2381 if (4 - CLUE_AT(state, i, j) < current_no) {
2382 #if 0
2383 fprintf(stderr, "detected error [%d,%d] in %s at line %d\n", i, j, __FUNCTION__, __LINE__);
2384 #endif
2385 sstate->solver_status = SOLVER_MISTAKE;
2386 return DIFF_EASY;
2387 }
2388 if (4 - CLUE_AT(state, i, j) == current_no) {
2389 if (square_setall(sstate, i, j, LINE_UNKNOWN, LINE_YES))
2390 diff = min(diff, DIFF_EASY);
2391 sstate->square_solved[SQUARE_INDEX(state, i, j)] = TRUE;
2392 continue;
2393 }
2394 }
2395
2396 check_caches(sstate);
2397
2398 /* Per-dot deductions */
2399 FORALL_DOTS(state, i, j) {
2400 if (sstate->dot_solved[DOT_INDEX(state, i, j)])
2401 continue;
2402
2403 switch (DOT_YES_COUNT(sstate, i, j)) {
2404 case 0:
2405 switch (DOT_NO_COUNT(sstate, i, j)) {
2406 case 3:
2407 #if 0
2408 fprintf(stderr, "dot [%d,%d]: 0 yes, 3 no\n", i, j);
2409 #endif
2410 dot_setall(sstate, i, j, LINE_UNKNOWN, LINE_NO);
2411 diff = min(diff, DIFF_EASY);
2412 /* fall through */
2413 case 4:
2414 sstate->dot_solved[DOT_INDEX(state, i, j)] = TRUE;
2415 break;
2416 }
2417 break;
2418 case 1:
2419 switch (DOT_NO_COUNT(sstate, i, j)) {
2420 case 2: /* 1 yes, 2 no */
2421 #if 0
2422 fprintf(stderr, "dot [%d,%d]: 1 yes, 2 no\n", i, j);
2423 #endif
2424 dot_setall(sstate, i, j, LINE_UNKNOWN, LINE_YES);
2425 diff = min(diff, DIFF_EASY);
2426 sstate->dot_solved[DOT_INDEX(state, i, j)] = TRUE;
2427 break;
2428 case 3: /* 1 yes, 3 no */
2429 #if 0
2430 fprintf(stderr, "detected error [%d,%d] in %s at line %d\n", i, j, __FUNCTION__, __LINE__);
2431 #endif
2432 sstate->solver_status = SOLVER_MISTAKE;
2433 return DIFF_EASY;
2434 }
2435 break;
2436 case 2:
2437 #if 0
2438 fprintf(stderr, "dot [%d,%d]: 2 yes\n", i, j);
2439 #endif
2440 dot_setall(sstate, i, j, LINE_UNKNOWN, LINE_NO);
2441 diff = min(diff, DIFF_EASY);
2442 sstate->dot_solved[DOT_INDEX(state, i, j)] = TRUE;
2443 break;
2444 case 3:
2445 case 4:
2446 #if 0
2447 fprintf(stderr, "detected error [%d,%d] in %s at line %d\n", i, j, __FUNCTION__, __LINE__);
2448 #endif
2449 sstate->solver_status = SOLVER_MISTAKE;
2450 return DIFF_EASY;
2451 }
2452 }
2453
2454 check_caches(sstate);
2455
2456 return diff;
2457 }
2458
2459 static int normal_mode_deductions(solver_state *sstate)
2460 {
2461 int i, j;
2462 game_state *state = sstate->state;
2463 enum dline_desc dd;
2464 enum diff diff = DIFF_MAX;
2465
2466 FORALL_SQUARES(state, i, j) {
2467 if (sstate->square_solved[SQUARE_INDEX(state, i, j)])
2468 continue;
2469
2470 if (CLUE_AT(state, i, j) < 0)
2471 continue;
2472
2473 switch (CLUE_AT(state, i, j)) {
2474 case 1:
2475 #if 0
2476 fprintf(stderr, "clue [%d,%d] is 1, doing dline ops\n",
2477 i, j);
2478 #endif
2479 FORALL_SQUARE_DLINES(dd) {
2480 /* At most one of any DLINE can be set */
2481 if (set_square_dline(state,
2482 sstate->normal->dot_atmostone,
2483 i, j, dd)) {
2484 diff = min(diff, DIFF_NORMAL);
2485 }
2486
2487 if (get_square_dline(state,
2488 sstate->normal->dot_atleastone,
2489 i, j, dd)) {
2490 /* This DLINE provides enough YESes to solve the clue */
2491 if (square_setboth_in_dline(sstate, OPP_DLINE(dd),
2492 i, j, LINE_NO)) {
2493 diff = min(diff, DIFF_EASY);
2494 }
2495 }
2496 }
2497
2498 break;
2499 case 2:
2500 /* If at least one of one DLINE is set, at most one
2501 * of the opposing one is and vice versa */
2502 #if 0
2503 fprintf(stderr, "clue [%d,%d] is 2, doing dline ops\n",
2504 i, j);
2505 #endif
2506 FORALL_SQUARE_DLINES(dd) {
2507 if (get_square_dline(state,
2508 sstate->normal->dot_atmostone,
2509 i, j, dd)) {
2510 if (set_square_opp_dline(state,
2511 sstate->normal->dot_atleastone,
2512 i, j, dd)) {
2513 diff = min(diff, DIFF_NORMAL);
2514 }
2515 }
2516 if (get_square_dline(state,
2517 sstate->normal->dot_atleastone,
2518 i, j, dd)) {
2519 if (set_square_opp_dline(state,
2520 sstate->normal->dot_atmostone,
2521 i, j, dd)) {
2522 diff = min(diff, DIFF_NORMAL);
2523 }
2524 }
2525 }
2526 break;
2527 case 3:
2528 #if 0
2529 fprintf(stderr, "clue [%d,%d] is 3, doing dline ops\n",
2530 i, j);
2531 #endif
2532 FORALL_SQUARE_DLINES(dd) {
2533 /* At least one of any DLINE must be set */
2534 if (set_square_dline(state,
2535 sstate->normal->dot_atleastone,
2536 i, j, dd)) {
2537 diff = min(diff, DIFF_NORMAL);
2538 }
2539
2540 if (get_square_dline(state,
2541 sstate->normal->dot_atmostone,
2542 i, j, dd)) {
2543 /* This DLINE provides enough NOs to solve the clue */
2544 if (square_setboth_in_dline(sstate, OPP_DLINE(dd),
2545 i, j, LINE_YES)) {
2546 diff = min(diff, DIFF_EASY);
2547 }
2548 }
2549 }
2550 break;
2551 }
2552 }
2553
2554 check_caches(sstate);
2555
2556 if (diff < DIFF_NORMAL)
2557 return diff;
2558
2559 FORALL_DOTS(state, i, j) {
2560 if (sstate->dot_solved[DOT_INDEX(state, i, j)])
2561 continue;
2562
2563 #if 0
2564 text = game_text_format(state);
2565 fprintf(stderr, "-----------------\n%s", text);
2566 sfree(text);
2567 #endif
2568
2569 switch (DOT_YES_COUNT(sstate, i, j)) {
2570 case 0:
2571 switch (DOT_NO_COUNT(sstate, i, j)) {
2572 case 1:
2573 /* Make note that at most one of each unknown DLINE
2574 * is YES */
2575 break;
2576 }
2577 break;
2578
2579 case 1:
2580 switch (DOT_NO_COUNT(sstate, i, j)) {
2581 case 1:
2582 /* 1 yes, 1 no, so exactly one of unknowns is
2583 * yes */
2584 #if 0
2585 fprintf(stderr, "dot [%d,%d]: 1 yes, 1 no\n", i, j);
2586 #endif
2587 FORALL_DOT_DLINES(dd) {
2588 if (dline_both_unknown(state,
2589 i, j, dd)) {
2590 if (set_dot_dline(state,
2591 sstate->normal->dot_atleastone,
2592 i, j, dd)) {
2593 diff = min(diff, DIFF_NORMAL);
2594 }
2595 }
2596 }
2597
2598 /* fall through */
2599 case 0:
2600 #if 0
2601 fprintf(stderr, "dot [%d,%d]: 1 yes, 0 or 1 no\n", i, j);
2602 #endif
2603 /* 1 yes, fewer than 2 no, so at most one of
2604 * unknowns is yes */
2605 FORALL_DOT_DLINES(dd) {
2606 if (dline_both_unknown(state,
2607 i, j, dd)) {
2608 if (set_dot_dline(state,
2609 sstate->normal->dot_atmostone,
2610 i, j, dd)) {
2611 diff = min(diff, DIFF_NORMAL);
2612 }
2613 }
2614 }
2615 break;
2616 }
2617 break;
2618 }
2619
2620 /* DLINE deductions that don't depend on the exact number of
2621 * LINE_YESs or LINE_NOs */
2622
2623 /* If at least one of a dline in a dot is YES, at most one
2624 * of the opposite dline to that dot must be YES. */
2625 FORALL_DOT_DLINES(dd) {
2626 if (get_dot_dline(state,
2627 sstate->normal->dot_atleastone,
2628 i, j, dd)) {
2629 if (set_dot_opp_dline(state,
2630 sstate->normal->dot_atmostone,
2631 i, j, dd)) {
2632 diff = min(diff, DIFF_NORMAL);
2633 }
2634 }
2635 }
2636
2637 if (dot_collapse_dlines(sstate, i, j))
2638 diff = min(diff, DIFF_EASY);
2639 }
2640 check_caches(sstate);
2641
2642 return diff;
2643 }
2644
2645 static int hard_mode_deductions(solver_state *sstate)
2646 {
2647 int i, j, a, b, s;
2648 game_state *state = sstate->state;
2649 const int h=state->h, w=state->w;
2650 enum direction dir1, dir2;
2651 int can1, can2, inv1, inv2;
2652 enum diff diff = DIFF_MAX;
2653 const struct dline *dl;
2654 enum dline_desc dd;
2655
2656 FORALL_SQUARES(state, i, j) {
2657 if (sstate->square_solved[SQUARE_INDEX(state, i, j)])
2658 continue;
2659
2660 switch (CLUE_AT(state, i, j)) {
2661 case -1:
2662 continue;
2663
2664 case 1:
2665 if (square_setall_identical(sstate, i, j, LINE_NO))
2666 diff = min(diff, DIFF_EASY);
2667 break;
2668 case 3:
2669 if (square_setall_identical(sstate, i, j, LINE_YES))
2670 diff = min(diff, DIFF_EASY);
2671 break;
2672 }
2673
2674 if (SQUARE_YES_COUNT(sstate, i, j) +
2675 SQUARE_NO_COUNT(sstate, i, j) == 2) {
2676 /* There are exactly two unknown lines bordering this
2677 * square. */
2678 if (SQUARE_YES_COUNT(sstate, i, j) + 1 ==
2679 CLUE_AT(state, i, j)) {
2680 /* They must be different */
2681 if (square_relate_2_unknowns(sstate, i, j, TRUE))
2682 diff = min(diff, DIFF_HARD);
2683 }
2684 }
2685 }
2686
2687 check_caches(sstate);
2688
2689 FORALL_DOTS(state, i, j) {
2690 if (DOT_YES_COUNT(sstate, i, j) == 1 &&
2691 DOT_NO_COUNT(sstate, i, j) == 1) {
2692 if (dot_relate_2_unknowns(sstate, i, j, TRUE))
2693 diff = min(diff, DIFF_HARD);
2694 continue;
2695 }
2696
2697 if (DOT_YES_COUNT(sstate, i, j) == 0 &&
2698 DOT_NO_COUNT(sstate, i, j) == 2) {
2699 if (dot_relate_2_unknowns(sstate, i, j, FALSE))
2700 diff = min(diff, DIFF_HARD);
2701 continue;
2702 }
2703 }
2704
2705 /* If two lines into a dot are related, the other two lines into that dot
2706 * are related in the same way. */
2707
2708 /* iter over points that aren't on edges */
2709 for (i = 1; i < w; ++i) {
2710 for (j = 1; j < h; ++j) {
2711 if (sstate->dot_solved[DOT_INDEX(state, i, j)])
2712 continue;
2713
2714 /* iter over directions */
2715 for (dir1 = 0; dir1 < 4; ++dir1) {
2716 for (dir2 = dir1+1; dir2 < 4; ++dir2) {
2717 /* canonify both lines */
2718 can1 = edsf_canonify
2719 (sstate->hard->linedsf,
2720 LINEDSF_INDEX(state, i, j, dir1),
2721 &inv1);
2722 can2 = edsf_canonify
2723 (sstate->hard->linedsf,
2724 LINEDSF_INDEX(state, i, j, dir2),
2725 &inv2);
2726 /* merge opposite lines */
2727 if (can1 == can2) {
2728 if (merge_lines(sstate,
2729 i, j, OPP_DIR(dir1),
2730 i, j, OPP_DIR(dir2),
2731 inv1 ^ inv2)) {
2732 diff = min(diff, DIFF_HARD);
2733 }
2734 }
2735 }
2736 }
2737 }
2738 }
2739
2740 /* If the state of a line is known, deduce the state of its canonical line
2741 * too. */
2742 FORALL_DOTS(state, i, j) {
2743 /* Do this even if the dot we're on is solved */
2744 if (i < w) {
2745 can1 = edsf_canonify(sstate->hard->linedsf,
2746 LINEDSF_INDEX(state, i, j, RIGHT),
2747 &inv1);
2748 linedsf_deindex(state, can1, &a, &b, &dir1);
2749 s = RIGHTOF_DOT(state, i, j);
2750 if (s != LINE_UNKNOWN)
2751 {
2752 if (set_line_bydot(sstate, a, b, dir1, inv1 ? OPP(s) : s))
2753 diff = min(diff, DIFF_EASY);
2754 }
2755 }
2756 if (j < h) {
2757 can1 = edsf_canonify(sstate->hard->linedsf,
2758 LINEDSF_INDEX(state, i, j, DOWN),
2759 &inv1);
2760 linedsf_deindex(state, can1, &a, &b, &dir1);
2761 s = BELOW_DOT(state, i, j);
2762 if (s != LINE_UNKNOWN)
2763 {
2764 if (set_line_bydot(sstate, a, b, dir1, inv1 ? OPP(s) : s))
2765 diff = min(diff, DIFF_EASY);
2766 }
2767 }
2768 }
2769
2770 /* Interactions between dline and linedsf */
2771 FORALL_DOTS(state, i, j) {
2772 if (sstate->dot_solved[DOT_INDEX(state, i, j)])
2773 continue;
2774
2775 FORALL_DOT_DLINES(dd) {
2776 dl = get_dline(dd);
2777 if (i == 0 && (dl->dir1 == LEFT || dl->dir2 == LEFT))
2778 continue;
2779 if (i == w && (dl->dir1 == RIGHT || dl->dir2 == RIGHT))
2780 continue;
2781 if (j == 0 && (dl->dir1 == UP || dl->dir2 == UP))
2782 continue;
2783 if (j == h && (dl->dir1 == DOWN || dl->dir2 == DOWN))
2784 continue;
2785
2786 if (get_dot_dline(state, sstate->normal->dot_atleastone,
2787 i, j, dd) &&
2788 get_dot_dline(state, sstate->normal->dot_atmostone,
2789 i, j, dd)) {
2790 /* atleastone && atmostone => inverse */
2791 if (merge_lines(sstate, i, j, dl->dir1, i, j, dl->dir2, 1)) {
2792 diff = min(diff, DIFF_HARD);
2793 }
2794 } else {
2795 /* don't have atleastone and atmostone for this dline */
2796 can1 = edsf_canonify(sstate->hard->linedsf,
2797 LINEDSF_INDEX(state, i, j, dl->dir1),
2798 &inv1);
2799 can2 = edsf_canonify(sstate->hard->linedsf,
2800 LINEDSF_INDEX(state, i, j, dl->dir2),
2801 &inv2);
2802 if (can1 == can2) {
2803 if (inv1 == inv2) {
2804 /* identical => collapse dline */
2805 if (get_dot_dline(state,
2806 sstate->normal->dot_atleastone,
2807 i, j, dd)) {
2808 if (set_line_bydot(sstate, i, j,
2809 dl->dir1, LINE_YES)) {
2810 diff = min(diff, DIFF_EASY);
2811 }
2812 if (set_line_bydot(sstate, i, j,
2813 dl->dir2, LINE_YES)) {
2814 diff = min(diff, DIFF_EASY);
2815 }
2816 } else if (get_dot_dline(state,
2817 sstate->normal->dot_atmostone,
2818 i, j, dd)) {
2819 if (set_line_bydot(sstate, i, j,
2820 dl->dir1, LINE_NO)) {
2821 diff = min(diff, DIFF_EASY);
2822 }
2823 if (set_line_bydot(sstate, i, j,
2824 dl->dir2, LINE_NO)) {
2825 diff = min(diff, DIFF_EASY);
2826 }
2827 }
2828 } else {
2829 /* inverse => atleastone && atmostone */
2830 if (set_dot_dline(state,
2831 sstate->normal->dot_atleastone,
2832 i, j, dd)) {
2833 diff = min(diff, DIFF_NORMAL);
2834 }
2835 if (set_dot_dline(state,
2836 sstate->normal->dot_atmostone,
2837 i, j, dd)) {
2838 diff = min(diff, DIFF_NORMAL);
2839 }
2840 }
2841 }
2842 }
2843 }
2844 }
2845
2846 /* If the state of the canonical line for line 'l' is known, deduce the
2847 * state of 'l' */
2848 FORALL_DOTS(state, i, j) {
2849 if (sstate->dot_solved[DOT_INDEX(state, i, j)])
2850 continue;
2851
2852 if (i < w) {
2853 can1 = edsf_canonify(sstate->hard->linedsf,
2854 LINEDSF_INDEX(state, i, j, RIGHT),
2855 &inv1);
2856 linedsf_deindex(state, can1, &a, &b, &dir1);
2857 s = get_line_status_from_point(state, a, b, dir1);
2858 if (s != LINE_UNKNOWN)
2859 {
2860 if (set_line_bydot(sstate, i, j, RIGHT, inv1 ? OPP(s) : s))
2861 diff = min(diff, DIFF_EASY);
2862 }
2863 }
2864 if (j < h) {
2865 can1 = edsf_canonify(sstate->hard->linedsf,
2866 LINEDSF_INDEX(state, i, j, DOWN),
2867 &inv1);
2868 linedsf_deindex(state, can1, &a, &b, &dir1);
2869 s = get_line_status_from_point(state, a, b, dir1);
2870 if (s != LINE_UNKNOWN)
2871 {
2872 if (set_line_bydot(sstate, i, j, DOWN, inv1 ? OPP(s) : s))
2873 diff = min(diff, DIFF_EASY);
2874 }
2875 }
2876 }
2877
2878 return diff;
2879 }
2880
2881 static int loop_deductions(solver_state *sstate)
2882 {
2883 int edgecount = 0, clues = 0, satclues = 0, sm1clues = 0;
2884 game_state *state = sstate->state;
2885 int shortest_chainlen = DOT_COUNT(state);
2886 int loop_found = FALSE;
2887 int d;
2888 int dots_connected;
2889 int progress = FALSE;
2890 int i, j;
2891
2892 /*
2893 * Go through the grid and update for all the new edges.
2894 * Since merge_dots() is idempotent, the simplest way to
2895 * do this is just to update for _all_ the edges.
2896 *
2897 * Also, while we're here, we count the edges, count the
2898 * clues, count the satisfied clues, and count the
2899 * satisfied-minus-one clues.
2900 */
2901 FORALL_DOTS(state, i, j) {
2902 if (RIGHTOF_DOT(state, i, j) == LINE_YES) {
2903 loop_found |= merge_dots(sstate, i, j, i+1, j);
2904 edgecount++;
2905 }
2906 if (BELOW_DOT(state, i, j) == LINE_YES) {
2907 loop_found |= merge_dots(sstate, i, j, i, j+1);
2908 edgecount++;
2909 }
2910
2911 if (CLUE_AT(state, i, j) >= 0) {
2912 int c = CLUE_AT(state, i, j);
2913 int o = SQUARE_YES_COUNT(sstate, i, j);
2914 if (o == c)
2915 satclues++;
2916 else if (o == c-1)
2917 sm1clues++;
2918 clues++;
2919 }
2920 }
2921
2922 for (i = 0; i < DOT_COUNT(state); ++i) {
2923 dots_connected =
2924 sstate->looplen[dsf_canonify(sstate->dotdsf, i)];
2925 if (dots_connected > 1)
2926 shortest_chainlen = min(shortest_chainlen, dots_connected);
2927 }
2928
2929 assert(sstate->solver_status == SOLVER_INCOMPLETE);
2930
2931 if (satclues == clues && shortest_chainlen == edgecount) {
2932 sstate->solver_status = SOLVER_SOLVED;
2933 /* This discovery clearly counts as progress, even if we haven't
2934 * just added any lines or anything */
2935 progress = TRUE;
2936 goto finished_loop_deductionsing;
2937 }
2938
2939 /*
2940 * Now go through looking for LINE_UNKNOWN edges which
2941 * connect two dots that are already in the same
2942 * equivalence class. If we find one, test to see if the
2943 * loop it would create is a solution.
2944 */
2945 FORALL_DOTS(state, i, j) {
2946 for (d = 0; d < 2; d++) {
2947 int i2, j2, eqclass, val;
2948
2949 if (d == 0) {
2950 if (RIGHTOF_DOT(state, i, j) !=
2951 LINE_UNKNOWN)
2952 continue;
2953 i2 = i+1;
2954 j2 = j;
2955 } else {
2956 if (BELOW_DOT(state, i, j) !=
2957 LINE_UNKNOWN) {
2958 continue;
2959 }
2960 i2 = i;
2961 j2 = j+1;
2962 }
2963
2964 eqclass = dsf_canonify(sstate->dotdsf, j * (state->w+1) + i);
2965 if (eqclass != dsf_canonify(sstate->dotdsf,
2966 j2 * (state->w+1) + i2)) {
2967 continue;
2968 }
2969
2970 val = LINE_NO; /* loop is bad until proven otherwise */
2971
2972 /*
2973 * This edge would form a loop. Next
2974 * question: how long would the loop be?
2975 * Would it equal the total number of edges
2976 * (plus the one we'd be adding if we added
2977 * it)?
2978 */
2979 if (sstate->looplen[eqclass] == edgecount + 1) {
2980 int sm1_nearby;
2981 int cx, cy;
2982
2983 /*
2984 * This edge would form a loop which
2985 * took in all the edges in the entire
2986 * grid. So now we need to work out
2987 * whether it would be a valid solution
2988 * to the puzzle, which means we have to
2989 * check if it satisfies all the clues.
2990 * This means that every clue must be
2991 * either satisfied or satisfied-minus-
2992 * 1, and also that the number of
2993 * satisfied-minus-1 clues must be at
2994 * most two and they must lie on either
2995 * side of this edge.
2996 */
2997 sm1_nearby = 0;
2998 cx = i - (j2-j);
2999 cy = j - (i2-i);
3000 if (CLUE_AT(state, cx,cy) >= 0 &&
3001 square_order(state, cx,cy, LINE_YES) ==
3002 CLUE_AT(state, cx,cy) - 1) {
3003 sm1_nearby++;
3004 }
3005 if (CLUE_AT(state, i, j) >= 0 &&
3006 SQUARE_YES_COUNT(sstate, i, j) ==
3007 CLUE_AT(state, i, j) - 1) {
3008 sm1_nearby++;
3009 }
3010 if (sm1clues == sm1_nearby &&
3011 sm1clues + satclues == clues) {
3012 val = LINE_YES; /* loop is good! */
3013 }
3014 }
3015
3016 /*
3017 * Right. Now we know that adding this edge
3018 * would form a loop, and we know whether
3019 * that loop would be a viable solution or
3020 * not.
3021 *
3022 * If adding this edge produces a solution,
3023 * then we know we've found _a_ solution but
3024 * we don't know that it's _the_ solution -
3025 * if it were provably the solution then
3026 * we'd have deduced this edge some time ago
3027 * without the need to do loop detection. So
3028 * in this state we return SOLVER_AMBIGUOUS,
3029 * which has the effect that hitting Solve
3030 * on a user-provided puzzle will fill in a
3031 * solution but using the solver to
3032 * construct new puzzles won't consider this
3033 * a reasonable deduction for the user to
3034 * make.
3035 */
3036 if (d == 0) {
3037 progress = set_line_bydot(sstate, i, j, RIGHT, val);
3038 assert(progress == TRUE);
3039 } else {
3040 progress = set_line_bydot(sstate, i, j, DOWN, val);
3041 assert(progress == TRUE);
3042 }
3043 if (val == LINE_YES) {
3044 sstate->solver_status = SOLVER_AMBIGUOUS;
3045 goto finished_loop_deductionsing;
3046 }
3047 }
3048 }
3049
3050 finished_loop_deductionsing:
3051 return progress ? DIFF_EASY : DIFF_MAX;
3052 }
3053
3054 /* This will return a dynamically allocated solver_state containing the (more)
3055 * solved grid */
3056 static solver_state *solve_game_rec(const solver_state *sstate_start,
3057 enum diff diff)
3058 {
3059 int i, j;
3060 int w, h;
3061 solver_state *sstate, *sstate_saved, *sstate_tmp;
3062 solver_state *sstate_rec_solved;
3063 int recursive_soln_count;
3064 int solver_progress;
3065 game_state *state;
3066
3067 /* Indicates which solver we should call next. This is a sensible starting
3068 * point */
3069 int current_solver = DIFF_EASY, next_solver;
3070 #ifdef SHOW_WORKING
3071 char *text;
3072 #endif
3073
3074 #if 0
3075 printf("solve_game_rec: recursion_remaining = %d\n",
3076 sstate_start->recursion_remaining);
3077 #endif
3078
3079 sstate = dup_solver_state(sstate_start);
3080
3081 /* Cache the values of some variables for readability */
3082 state = sstate->state;
3083 h = state->h;
3084 w = state->w;
3085
3086 sstate_saved = NULL;
3087
3088 nonrecursive_solver:
3089 solver_progress = FALSE;
3090
3091 check_caches(sstate);
3092
3093 do {
3094 #ifdef SHOW_WORKING
3095 text = game_text_format(state);
3096 fprintf(stderr, "-----------------\n%s", text);
3097 sfree(text);
3098 #endif
3099
3100 if (sstate->solver_status == SOLVER_MISTAKE)
3101 return sstate;
3102
3103 /* fprintf(stderr, "Invoking solver %d\n", current_solver); */
3104 next_solver = solver_fns[current_solver](sstate);
3105
3106 if (next_solver == DIFF_MAX) {
3107 /* fprintf(stderr, "Current solver failed\n"); */
3108 if (current_solver < diff && current_solver + 1 < DIFF_MAX) {
3109 /* Try next beefier solver */
3110 next_solver = current_solver + 1;
3111 } else {
3112 /* fprintf(stderr, "Doing loop deductions\n"); */
3113 next_solver = loop_deductions(sstate);
3114 }
3115 }
3116
3117 if (sstate->solver_status == SOLVER_SOLVED ||
3118 sstate->solver_status == SOLVER_AMBIGUOUS) {
3119 /* fprintf(stderr, "Solver completed\n"); */
3120 break;
3121 }
3122
3123 /* Once we've looped over all permitted solvers then the loop
3124 * deductions without making any progress, we'll exit this while loop */
3125 current_solver = next_solver;
3126 } while (current_solver < DIFF_MAX);
3127
3128 if (sstate->solver_status == SOLVER_SOLVED ||
3129 sstate->solver_status == SOLVER_AMBIGUOUS) {
3130 /* s/LINE_UNKNOWN/LINE_NO/g */
3131 array_setall(sstate->state->hl, LINE_UNKNOWN, LINE_NO,
3132 HL_COUNT(sstate->state));
3133 array_setall(sstate->state->vl, LINE_UNKNOWN, LINE_NO,
3134 VL_COUNT(sstate->state));
3135 return sstate;
3136 }
3137
3138 /* Perform recursive calls */
3139 if (sstate->recursion_remaining) {
3140 sstate_saved = dup_solver_state(sstate);
3141
3142 sstate->recursion_remaining--;
3143
3144 recursive_soln_count = 0;
3145 sstate_rec_solved = NULL;
3146
3147 /* Memory management:
3148 * sstate_saved won't be modified but needs to be freed when we have
3149 * finished with it.
3150 * sstate is expected to contain our 'best' solution by the time we
3151 * finish this section of code. It's the thing we'll try adding lines
3152 * to, seeing if they make it more solvable.
3153 * If sstate_rec_solved is non-NULL, it will supersede sstate
3154 * eventually. sstate_tmp should not hold a value persistently.
3155 */
3156
3157 /* NB SOLVER_AMBIGUOUS is like SOLVER_SOLVED except the solver is aware
3158 * of the possibility of additional solutions. So as soon as we have a
3159 * SOLVER_AMBIGUOUS we can safely propagate it back to our caller, but
3160 * if we get a SOLVER_SOLVED we want to keep trying in case we find
3161 * further solutions and have to mark it ambiguous.
3162 */
3163
3164 #define DO_RECURSIVE_CALL(dir_dot) \
3165 if (dir_dot(sstate->state, i, j) == LINE_UNKNOWN) { \
3166 debug(("Trying " #dir_dot " at [%d,%d]\n", i, j)); \
3167 LV_##dir_dot(sstate->state, i, j) = LINE_YES; \
3168 sstate_tmp = solve_game_rec(sstate, diff); \
3169 switch (sstate_tmp->solver_status) { \
3170 case SOLVER_AMBIGUOUS: \
3171 debug(("Solver ambiguous, returning\n")); \
3172 sstate_rec_solved = sstate_tmp; \
3173 goto finished_recursion; \
3174 case SOLVER_SOLVED: \
3175 switch (++recursive_soln_count) { \
3176 case 1: \
3177 debug(("One solution found\n")); \
3178 sstate_rec_solved = sstate_tmp; \
3179 break; \
3180 case 2: \
3181 debug(("Ambiguous solutions found\n")); \
3182 free_solver_state(sstate_tmp); \
3183 sstate_rec_solved->solver_status = SOLVER_AMBIGUOUS; \
3184 goto finished_recursion; \
3185 default: \
3186 assert(!"recursive_soln_count out of range"); \
3187 break; \
3188 } \
3189 break; \
3190 case SOLVER_MISTAKE: \
3191 debug(("Non-solution found\n")); \
3192 free_solver_state(sstate_tmp); \
3193 free_solver_state(sstate_saved); \
3194 LV_##dir_dot(sstate->state, i, j) = LINE_NO; \
3195 goto nonrecursive_solver; \
3196 case SOLVER_INCOMPLETE: \
3197 debug(("Recursive step inconclusive\n")); \
3198 free_solver_state(sstate_tmp); \
3199 break; \
3200 } \
3201 free_solver_state(sstate); \
3202 sstate = dup_solver_state(sstate_saved); \
3203 }
3204
3205 FORALL_DOTS(state, i, j) {
3206 /* Only perform recursive calls on 'loose ends' */
3207 if (DOT_YES_COUNT(sstate, i, j) == 1) {
3208 DO_RECURSIVE_CALL(LEFTOF_DOT);
3209 DO_RECURSIVE_CALL(RIGHTOF_DOT);
3210 DO_RECURSIVE_CALL(ABOVE_DOT);
3211 DO_RECURSIVE_CALL(BELOW_DOT);
3212 }
3213 }
3214
3215 finished_recursion:
3216
3217 if (sstate_rec_solved) {
3218 free_solver_state(sstate);
3219 sstate = sstate_rec_solved;
3220 }
3221 }
3222
3223 return sstate;
3224 }
3225
3226 #if 0
3227 #define HANDLE_DLINE(dline, dir1_sq, dir2_sq, a, b) \
3228 if (sstate->normal->dot_atmostone[i+a + (sstate->state->w + 1) * (j+b)] & \
3229 1<<dline) { \
3230 if (square_order(sstate->state, i, j, LINE_UNKNOWN) - 1 == \
3231 CLUE_AT(sstate->state, i, j) - '0') { \
3232 square_setall(sstate->state, i, j, LINE_UNKNOWN, LINE_YES); \
3233 /* XXX the following may overwrite known data! */ \
3234 dir1_sq(sstate->state, i, j) = LINE_UNKNOWN; \
3235 dir2_sq(sstate->state, i, j) = LINE_UNKNOWN; \
3236 } \
3237 }
3238 SQUARE_DLINES;
3239 #undef HANDLE_DLINE
3240 #endif
3241
3242 static char *solve_game(game_state *state, game_state *currstate,
3243 char *aux, char **error)
3244 {
3245 char *soln = NULL;
3246 solver_state *sstate, *new_sstate;
3247
3248 sstate = new_solver_state(state, DIFF_MAX);
3249 new_sstate = solve_game_rec(sstate, DIFF_MAX);
3250
3251 if (new_sstate->solver_status == SOLVER_SOLVED) {
3252 soln = encode_solve_move(new_sstate->state);
3253 } else if (new_sstate->solver_status == SOLVER_AMBIGUOUS) {
3254 soln = encode_solve_move(new_sstate->state);
3255 /**error = "Solver found ambiguous solutions"; */
3256 } else {
3257 soln = encode_solve_move(new_sstate->state);
3258 /**error = "Solver failed"; */
3259 }
3260
3261 free_solver_state(new_sstate);
3262 free_solver_state(sstate);
3263
3264 return soln;
3265 }
3266
3267 /* ----------------------------------------------------------------------
3268 * Drawing and mouse-handling
3269 */
3270
3271 static char *interpret_move(game_state *state, game_ui *ui, game_drawstate *ds,
3272 int x, int y, int button)
3273 {
3274 int hl_selected;
3275 int i, j, p, q;
3276 char *ret, buf[80];
3277 char button_char = ' ';
3278 enum line_state old_state;
3279
3280 button &= ~MOD_MASK;
3281
3282 /* Around each line is a diamond-shaped region where points within that
3283 * region are closer to this line than any other. We assume any click
3284 * within a line's diamond was meant for that line. It would all be a lot
3285 * simpler if the / and % operators respected modulo arithmetic properly
3286 * for negative numbers. */
3287
3288 x -= BORDER;
3289 y -= BORDER;
3290
3291 /* Get the coordinates of the square the click was in */
3292 i = (x + TILE_SIZE) / TILE_SIZE - 1;
3293 j = (y + TILE_SIZE) / TILE_SIZE - 1;
3294
3295 /* Get the precise position inside square [i,j] */
3296 p = (x + TILE_SIZE) % TILE_SIZE;
3297 q = (y + TILE_SIZE) % TILE_SIZE;
3298
3299 /* After this bit of magic [i,j] will correspond to the point either above
3300 * or to the left of the line selected */
3301 if (p > q) {
3302 if (TILE_SIZE - p > q) {
3303 hl_selected = TRUE;
3304 } else {
3305 hl_selected = FALSE;
3306 ++i;
3307 }
3308 } else {
3309 if (TILE_SIZE - q > p) {
3310 hl_selected = FALSE;
3311 } else {
3312 hl_selected = TRUE;
3313 ++j;
3314 }
3315 }
3316
3317 if (i < 0 || j < 0)
3318 return NULL;
3319
3320 if (hl_selected) {
3321 if (i >= state->w || j >= state->h + 1)
3322 return NULL;
3323 } else {
3324 if (i >= state->w + 1 || j >= state->h)
3325 return NULL;
3326 }
3327
3328 /* I think it's only possible to play this game with mouse clicks, sorry */
3329 /* Maybe will add mouse drag support some time */
3330 if (hl_selected)
3331 old_state = RIGHTOF_DOT(state, i, j);
3332 else
3333 old_state = BELOW_DOT(state, i, j);
3334
3335 switch (button) {
3336 case LEFT_BUTTON:
3337 switch (old_state) {
3338 case LINE_UNKNOWN:
3339 button_char = 'y';
3340 break;
3341 case LINE_YES:
3342 case LINE_NO:
3343 button_char = 'u';
3344 break;
3345 }
3346 break;
3347 case MIDDLE_BUTTON:
3348 button_char = 'u';
3349 break;
3350 case RIGHT_BUTTON:
3351 switch (old_state) {
3352 case LINE_UNKNOWN:
3353 button_char = 'n';
3354 break;
3355 case LINE_NO:
3356 case LINE_YES:
3357 button_char = 'u';
3358 break;
3359 }
3360 break;
3361 default:
3362 return NULL;
3363 }
3364
3365
3366 sprintf(buf, "%d,%d%c%c", i, j, (int)(hl_selected ? 'h' : 'v'), (int)button_char);
3367 ret = dupstr(buf);
3368
3369 return ret;
3370 }
3371
3372 static game_state *execute_move(game_state *state, char *move)
3373 {
3374 int i, j;
3375 game_state *newstate = dup_game(state);
3376
3377 if (move[0] == 'S') {
3378 move++;
3379 newstate->cheated = TRUE;
3380 }
3381
3382 while (*move) {
3383 i = atoi(move);
3384 move = strchr(move, ',');
3385 if (!move)
3386 goto fail;
3387 j = atoi(++move);
3388 move += strspn(move, "1234567890");
3389 switch (*(move++)) {
3390 case 'h':
3391 if (i >= newstate->w || j > newstate->h)
3392 goto fail;
3393 switch (*(move++)) {
3394 case 'y':
3395 LV_RIGHTOF_DOT(newstate, i, j) = LINE_YES;
3396 break;
3397 case 'n':
3398 LV_RIGHTOF_DOT(newstate, i, j) = LINE_NO;
3399 break;
3400 case 'u':
3401 LV_RIGHTOF_DOT(newstate, i, j) = LINE_UNKNOWN;
3402 break;
3403 default:
3404 goto fail;
3405 }
3406 break;
3407 case 'v':
3408 if (i > newstate->w || j >= newstate->h)
3409 goto fail;
3410 switch (*(move++)) {
3411 case 'y':
3412 LV_BELOW_DOT(newstate, i, j) = LINE_YES;
3413 break;
3414 case 'n':
3415 LV_BELOW_DOT(newstate, i, j) = LINE_NO;
3416 break;
3417 case 'u':
3418 LV_BELOW_DOT(newstate, i, j) = LINE_UNKNOWN;
3419 break;
3420 default:
3421 goto fail;
3422 }
3423 break;
3424 default:
3425 goto fail;
3426 }
3427 }
3428
3429 /*
3430 * Check for completion.
3431 */
3432 i = 0; /* placate optimiser */
3433 for (j = 0; j <= newstate->h; j++) {
3434 for (i = 0; i < newstate->w; i++)
3435 if (LV_RIGHTOF_DOT(newstate, i, j) == LINE_YES)
3436 break;
3437 if (i < newstate->w)
3438 break;
3439 }
3440 if (j <= newstate->h) {
3441 int prevdir = 'R';
3442 int x = i, y = j;
3443 int looplen, count;
3444
3445 /*
3446 * We've found a horizontal edge at (i,j). Follow it round
3447 * to see if it's part of a loop.
3448 */
3449 looplen = 0;
3450 while (1) {
3451 int order = dot_order(newstate, x, y, LINE_YES);
3452 if (order != 2)
3453 goto completion_check_done;
3454
3455 if (LEFTOF_DOT(newstate, x, y) == LINE_YES && prevdir != 'L') {
3456 x--;
3457 prevdir = 'R';
3458 } else if (RIGHTOF_DOT(newstate, x, y) == LINE_YES &&
3459 prevdir != 'R') {
3460 x++;
3461 prevdir = 'L';
3462 } else if (ABOVE_DOT(newstate, x, y) == LINE_YES &&
3463 prevdir != 'U') {
3464 y--;
3465 prevdir = 'D';
3466 } else if (BELOW_DOT(newstate, x, y) == LINE_YES &&
3467 prevdir != 'D') {
3468 y++;
3469 prevdir = 'U';
3470 } else {
3471 assert(!"Can't happen"); /* dot_order guarantees success */
3472 }
3473
3474 looplen++;
3475
3476 if (x == i && y == j)
3477 break;
3478 }
3479
3480 if (x != i || y != j || looplen == 0)
3481 goto completion_check_done;
3482
3483 /*
3484 * We've traced our way round a loop, and we know how many
3485 * line segments were involved. Count _all_ the line
3486 * segments in the grid, to see if the loop includes them
3487 * all.
3488 */
3489 count = 0;
3490 FORALL_DOTS(newstate, i, j) {
3491 count += ((RIGHTOF_DOT(newstate, i, j) == LINE_YES) +
3492 (BELOW_DOT(newstate, i, j) == LINE_YES));
3493 }
3494 assert(count >= looplen);
3495 if (count != looplen)
3496 goto completion_check_done;
3497
3498 /*
3499 * The grid contains one closed loop and nothing else.
3500 * Check that all the clues are satisfied.
3501 */
3502 FORALL_SQUARES(newstate, i, j) {
3503 if (CLUE_AT(newstate, i, j) >= 0) {
3504 if (square_order(newstate, i, j, LINE_YES) !=
3505 CLUE_AT(newstate, i, j)) {
3506 goto completion_check_done;
3507 }
3508 }
3509 }
3510
3511 /*
3512 * Completed!
3513 */
3514 newstate->solved = TRUE;
3515 }
3516
3517 completion_check_done:
3518 return newstate;
3519
3520 fail:
3521 free_game(newstate);
3522 return NULL;
3523 }
3524
3525 /* ----------------------------------------------------------------------
3526 * Drawing routines.
3527 */
3528 static void game_redraw(drawing *dr, game_drawstate *ds, game_state *oldstate,
3529 game_state *state, int dir, game_ui *ui,
3530 float animtime, float flashtime)
3531 {
3532 int i, j, n;
3533 char c[2];
3534 int line_colour, flash_changed;
3535 int clue_mistake;
3536
3537 if (!ds->started) {
3538 /*
3539 * The initial contents of the window are not guaranteed and
3540 * can vary with front ends. To be on the safe side, all games
3541 * should start by drawing a big background-colour rectangle
3542 * covering the whole window.
3543 */
3544 draw_rect(dr, 0, 0, SIZE(state->w), SIZE(state->h), COL_BACKGROUND);
3545
3546 /* Draw dots */
3547 FORALL_DOTS(state, i, j) {
3548 draw_rect(dr,
3549 BORDER + i * TILE_SIZE - LINEWIDTH/2,
3550 BORDER + j * TILE_SIZE - LINEWIDTH/2,
3551 LINEWIDTH, LINEWIDTH, COL_FOREGROUND);
3552 }
3553
3554 /* Draw clues */
3555 FORALL_SQUARES(state, i, j) {
3556 c[0] = CLUE2CHAR(CLUE_AT(state, i, j));
3557 c[1] = '\0';
3558 draw_text(dr,
3559 BORDER + i * TILE_SIZE + TILE_SIZE/2,
3560 BORDER + j * TILE_SIZE + TILE_SIZE/2,
3561 FONT_VARIABLE, TILE_SIZE/2,
3562 ALIGN_VCENTRE | ALIGN_HCENTRE, COL_FOREGROUND, c);
3563 }
3564 draw_update(dr, 0, 0,
3565 state->w * TILE_SIZE + 2*BORDER + 1,
3566 state->h * TILE_SIZE + 2*BORDER + 1);
3567 ds->started = TRUE;
3568 }
3569
3570 if (flashtime > 0 &&
3571 (flashtime <= FLASH_TIME/3 ||
3572 flashtime >= FLASH_TIME*2/3)) {
3573 flash_changed = !ds->flashing;
3574 ds->flashing = TRUE;
3575 line_colour = COL_HIGHLIGHT;
3576 } else {
3577 flash_changed = ds->flashing;
3578 ds->flashing = FALSE;
3579 line_colour = COL_FOREGROUND;
3580 }
3581
3582 #define CROSS_SIZE (3 * LINEWIDTH / 2)
3583
3584 /* Redraw clue colours if necessary */
3585 FORALL_SQUARES(state, i, j) {
3586 n = CLUE_AT(state, i, j);
3587 if (n < 0)
3588 continue;
3589
3590 assert(n >= 0 && n <= 4);
3591
3592 c[0] = CLUE2CHAR(CLUE_AT(state, i, j));
3593 c[1] = '\0';
3594
3595 clue_mistake = (square_order(state, i, j, LINE_YES) > n ||
3596 square_order(state, i, j, LINE_NO ) > (4-n));
3597
3598 if (clue_mistake != ds->clue_error[SQUARE_INDEX(state, i, j)]) {
3599 draw_rect(dr,
3600 BORDER + i * TILE_SIZE + CROSS_SIZE,
3601 BORDER + j * TILE_SIZE + CROSS_SIZE,
3602 TILE_SIZE - CROSS_SIZE * 2, TILE_SIZE - CROSS_SIZE * 2,
3603 COL_BACKGROUND);
3604 draw_text(dr,
3605 BORDER + i * TILE_SIZE + TILE_SIZE/2,
3606 BORDER + j * TILE_SIZE + TILE_SIZE/2,
3607 FONT_VARIABLE, TILE_SIZE/2,
3608 ALIGN_VCENTRE | ALIGN_HCENTRE,
3609 clue_mistake ? COL_MISTAKE : COL_FOREGROUND, c);
3610 draw_update(dr, i * TILE_SIZE + BORDER, j * TILE_SIZE + BORDER,
3611 TILE_SIZE, TILE_SIZE);
3612
3613 ds->clue_error[SQUARE_INDEX(state, i, j)] = clue_mistake;
3614 }
3615 }
3616
3617 /* I've also had a request to colour lines red if they make a non-solution
3618 * loop, or if more than two lines go into any point. I think that would
3619 * be good some time. */
3620
3621 #define CLEAR_VL(i, j) \
3622 do { \
3623 draw_rect(dr, \
3624 BORDER + i * TILE_SIZE - CROSS_SIZE, \
3625 BORDER + j * TILE_SIZE + LINEWIDTH - LINEWIDTH/2, \
3626 CROSS_SIZE * 2, \
3627 TILE_SIZE - LINEWIDTH, \
3628 COL_BACKGROUND); \
3629 draw_update(dr, \
3630 BORDER + i * TILE_SIZE - CROSS_SIZE, \
3631 BORDER + j * TILE_SIZE - CROSS_SIZE, \
3632 CROSS_SIZE*2, \
3633 TILE_SIZE + CROSS_SIZE*2); \
3634 } while (0)
3635
3636 #define CLEAR_HL(i, j) \
3637 do { \
3638 draw_rect(dr, \
3639 BORDER + i * TILE_SIZE + LINEWIDTH - LINEWIDTH/2, \
3640 BORDER + j * TILE_SIZE - CROSS_SIZE, \
3641 TILE_SIZE - LINEWIDTH, \
3642 CROSS_SIZE * 2, \
3643 COL_BACKGROUND); \
3644 draw_update(dr, \
3645 BORDER + i * TILE_SIZE - CROSS_SIZE, \
3646 BORDER + j * TILE_SIZE - CROSS_SIZE, \
3647 TILE_SIZE + CROSS_SIZE*2, \
3648 CROSS_SIZE*2); \
3649 } while (0)
3650
3651 /* Vertical lines */
3652 FORALL_VL(state, i, j) {
3653 switch (BELOW_DOT(state, i, j)) {
3654 case LINE_UNKNOWN:
3655 if (ds->vl[VL_INDEX(state, i, j)] != BELOW_DOT(state, i, j)) {
3656 CLEAR_VL(i, j);
3657 }
3658 break;
3659 case LINE_YES:
3660 if (ds->vl[VL_INDEX(state, i, j)] != BELOW_DOT(state, i, j) ||
3661 flash_changed) {
3662 CLEAR_VL(i, j);
3663 draw_rect(dr,
3664 BORDER + i * TILE_SIZE - LINEWIDTH/2,
3665 BORDER + j * TILE_SIZE + LINEWIDTH - LINEWIDTH/2,
3666 LINEWIDTH, TILE_SIZE - LINEWIDTH,
3667 line_colour);
3668 }
3669 break;
3670 case LINE_NO:
3671 if (ds->vl[VL_INDEX(state, i, j)] != BELOW_DOT(state, i, j)) {
3672 CLEAR_VL(i, j);
3673 draw_line(dr,
3674 BORDER + i * TILE_SIZE - CROSS_SIZE,
3675 BORDER + j * TILE_SIZE + TILE_SIZE/2 - CROSS_SIZE,
3676 BORDER + i * TILE_SIZE + CROSS_SIZE - 1,
3677 BORDER + j * TILE_SIZE + TILE_SIZE/2 + CROSS_SIZE - 1,
3678 COL_FOREGROUND);
3679 draw_line(dr,
3680 BORDER + i * TILE_SIZE + CROSS_SIZE - 1,
3681 BORDER + j * TILE_SIZE + TILE_SIZE/2 - CROSS_SIZE,
3682 BORDER + i * TILE_SIZE - CROSS_SIZE,
3683 BORDER + j * TILE_SIZE + TILE_SIZE/2 + CROSS_SIZE - 1,
3684 COL_FOREGROUND);
3685 }
3686 break;
3687 }
3688 ds->vl[VL_INDEX(state, i, j)] = BELOW_DOT(state, i, j);
3689 }
3690
3691 /* Horizontal lines */
3692 FORALL_HL(state, i, j) {
3693 switch (RIGHTOF_DOT(state, i, j)) {
3694 case LINE_UNKNOWN:
3695 if (ds->hl[HL_INDEX(state, i, j)] != RIGHTOF_DOT(state, i, j)) {
3696 CLEAR_HL(i, j);
3697 }
3698 break;
3699 case LINE_YES:
3700 if (ds->hl[HL_INDEX(state, i, j)] != RIGHTOF_DOT(state, i, j) ||
3701 flash_changed) {
3702 CLEAR_HL(i, j);
3703 draw_rect(dr,
3704 BORDER + i * TILE_SIZE + LINEWIDTH - LINEWIDTH/2,
3705 BORDER + j * TILE_SIZE - LINEWIDTH/2,
3706 TILE_SIZE - LINEWIDTH, LINEWIDTH,
3707 line_colour);
3708 }
3709 break;
3710 case LINE_NO:
3711 if (ds->hl[HL_INDEX(state, i, j)] != RIGHTOF_DOT(state, i, j)) {
3712 CLEAR_HL(i, j);
3713 draw_line(dr,
3714 BORDER + i * TILE_SIZE + TILE_SIZE/2 - CROSS_SIZE,
3715 BORDER + j * TILE_SIZE + CROSS_SIZE - 1,
3716 BORDER + i * TILE_SIZE + TILE_SIZE/2 + CROSS_SIZE - 1,
3717 BORDER + j * TILE_SIZE - CROSS_SIZE,
3718 COL_FOREGROUND);
3719 draw_line(dr,
3720 BORDER + i * TILE_SIZE + TILE_SIZE/2 - CROSS_SIZE,
3721 BORDER + j * TILE_SIZE - CROSS_SIZE,
3722 BORDER + i * TILE_SIZE + TILE_SIZE/2 + CROSS_SIZE - 1,
3723 BORDER + j * TILE_SIZE + CROSS_SIZE - 1,
3724 COL_FOREGROUND);
3725 break;
3726 }
3727 }
3728 ds->hl[HL_INDEX(state, i, j)] = RIGHTOF_DOT(state, i, j);
3729 }
3730 }
3731
3732 static float game_flash_length(game_state *oldstate, game_state *newstate,
3733 int dir, game_ui *ui)
3734 {
3735 if (!oldstate->solved && newstate->solved &&
3736 !oldstate->cheated && !newstate->cheated) {
3737 return FLASH_TIME;
3738 }
3739
3740 return 0.0F;
3741 }
3742
3743 static void game_print_size(game_params *params, float *x, float *y)
3744 {
3745 int pw, ph;
3746
3747 /*
3748 * I'll use 7mm squares by default.
3749 */
3750 game_compute_size(params, 700, &pw, &ph);
3751 *x = pw / 100.0F;
3752 *y = ph / 100.0F;
3753 }
3754
3755 static void game_print(drawing *dr, game_state *state, int tilesize)
3756 {
3757 int ink = print_mono_colour(dr, 0);
3758 int x, y;
3759 game_drawstate ads, *ds = &ads;
3760
3761 game_set_size(dr, ds, NULL, tilesize);
3762
3763 /*
3764 * Dots. I'll deliberately make the dots a bit wider than the
3765 * lines, so you can still see them. (And also because it's
3766 * annoyingly tricky to make them _exactly_ the same size...)
3767 */
3768 FORALL_DOTS(state, x, y) {
3769 draw_circle(dr, BORDER + x * TILE_SIZE, BORDER + y * TILE_SIZE,
3770 LINEWIDTH, ink, ink);
3771 }
3772
3773 /*
3774 * Clues.
3775 */
3776 FORALL_SQUARES(state, x, y) {
3777 if (CLUE_AT(state, x, y) >= 0) {
3778 char c[2];
3779
3780 c[0] = CLUE2CHAR(CLUE_AT(state, x, y));
3781 c[1] = '\0';
3782 draw_text(dr,
3783 BORDER + x * TILE_SIZE + TILE_SIZE/2,
3784 BORDER + y * TILE_SIZE + TILE_SIZE/2,
3785 FONT_VARIABLE, TILE_SIZE/2,
3786 ALIGN_VCENTRE | ALIGN_HCENTRE, ink, c);
3787 }
3788 }
3789
3790 /*
3791 * Lines. (At the moment, I'm not bothering with crosses.)
3792 */
3793 FORALL_VL(state, x, y) {
3794 if (RIGHTOF_DOT(state, x, y) == LINE_YES)
3795 draw_rect(dr, BORDER + x * TILE_SIZE,
3796 BORDER + y * TILE_SIZE - LINEWIDTH/2,
3797 TILE_SIZE, (LINEWIDTH/2) * 2 + 1, ink);
3798 }
3799
3800 FORALL_HL(state, x, y) {
3801 if (BELOW_DOT(state, x, y) == LINE_YES)
3802 draw_rect(dr, BORDER + x * TILE_SIZE - LINEWIDTH/2,
3803 BORDER + y * TILE_SIZE,
3804 (LINEWIDTH/2) * 2 + 1, TILE_SIZE, ink);
3805 }
3806 }
3807
3808 #ifdef COMBINED
3809 #define thegame loopy
3810 #endif
3811
3812 const struct game thegame = {
3813 "Loopy", "games.loopy",
3814 default_params,
3815 game_fetch_preset,
3816 decode_params,
3817 encode_params,
3818 free_params,
3819 dup_params,
3820 TRUE, game_configure, custom_params,
3821 validate_params,
3822 new_game_desc,
3823 validate_desc,
3824 new_game,
3825 dup_game,
3826 free_game,
3827 1, solve_game,
3828 TRUE, game_text_format,
3829 new_ui,
3830 free_ui,
3831 encode_ui,
3832 decode_ui,
3833 game_changed_state,
3834 interpret_move,
3835 execute_move,
3836 PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
3837 game_colours,
3838 game_new_drawstate,
3839 game_free_drawstate,
3840 game_redraw,
3841 game_anim_length,
3842 game_flash_length,
3843 TRUE, FALSE, game_print_size, game_print,
3844 FALSE /* wants_statusbar */,
3845 FALSE, game_timing_state,
3846 0, /* mouse_priorities */
3847 };