2 * lightup.c: Implementation of the Nikoli game 'Light Up'.
4 * Possible future solver enhancements:
6 * - In a situation where two clues are diagonally adjacent, you can
7 * deduce bounds on the number of lights shared between them. For
8 * instance, suppose a 3 clue is diagonally adjacent to a 1 clue:
9 * of the two squares adjacent to both clues, at least one must be
10 * a light (or the 3 would be unsatisfiable) and yet at most one
11 * must be a light (or the 1 would be overcommitted), so in fact
12 * _exactly_ one must be a light, and hence the other two squares
13 * adjacent to the 3 must also be lights and the other two adjacent
14 * to the 1 must not. Likewise if the 3 is replaced with a 2 but
15 * one of its other two squares is known not to be a light, and so
18 * - In a situation where two clues are orthogonally separated (not
19 * necessarily directly adjacent), you may be able to deduce
20 * something about the squares that align with each other. For
21 * instance, suppose two clues are vertically adjacent. Consider
22 * the pair of squares A,B horizontally adjacent to the top clue,
23 * and the pair C,D horizontally adjacent to the bottom clue.
24 * Assuming no intervening obstacles, A and C align with each other
25 * and hence at most one of them can be a light, and B and D
26 * likewise, so we must have at most two lights between the four
27 * squares. So if the clues indicate that there are at _least_ two
28 * lights in those four squares because the top clue requires at
29 * least one of AB to be a light and the bottom one requires at
30 * least one of CD, then we can in fact deduce that there are
31 * _exactly_ two lights between the four squares, and fill in the
32 * other squares adjacent to each clue accordingly. For instance,
33 * if both clues are 3s, then we instantly deduce that all four of
34 * the squares _vertically_ adjacent to the two clues must be
35 * lights. (For that to happen, of course, there'd also have to be
36 * a black square in between the clues, so the two inner lights
37 * don't light each other.)
39 * - I haven't thought it through carefully, but there's always the
40 * possibility that both of the above deductions are special cases
41 * of some more general pattern which can be made computationally
55 * In standalone solver mode, `verbose' is a variable which can be
56 * set by command-line option; in debugging mode it's simply always
59 #if defined STANDALONE_SOLVER
60 #define SOLVER_DIAGNOSTICS
63 #define debug(x) printf x
64 #elif defined SOLVER_DIAGNOSTICS
68 /* --- Constants, structure definitions, etc. --- */
70 #define PREFERRED_TILE_SIZE 32
71 #define TILE_SIZE (ds->tilesize)
72 #define BORDER (TILE_SIZE / 2)
73 #define TILE_RADIUS (ds->crad)
75 #define COORD(x) ( (x) * TILE_SIZE + BORDER )
76 #define FROMCOORD(x) ( ((x) - BORDER + TILE_SIZE) / TILE_SIZE - 1 )
78 #define FLASH_TIME 0.30F
83 COL_BLACK, /* black */
84 COL_LIGHT, /* white */
91 enum { SYMM_NONE, SYMM_REF2, SYMM_ROT2, SYMM_REF4, SYMM_ROT4, SYMM_MAX };
97 int blackpc; /* %age of black squares */
99 int difficulty; /* 0 to DIFFCOUNT */
104 /* flags for black squares */
105 #define F_NUMBERED 2 /* it has a number attached */
106 #define F_NUMBERUSED 4 /* this number was useful for solving */
108 /* flags for non-black squares */
109 #define F_IMPOSSIBLE 8 /* can't put a light here */
116 int *lights; /* For black squares, (optionally) the number
117 of surrounding lights. For non-black squares,
118 the number of times it's lit. size h*w*/
119 unsigned int *flags; /* size h*w */
120 int completed, used_solve;
123 #define GRID(gs,grid,x,y) (gs->grid[(y)*((gs)->w) + (x)])
125 /* A ll_data holds information about which lights would be lit by
126 * a particular grid location's light (or conversely, which locations
127 * could light a specific other location). */
128 /* most things should consider this struct opaque. */
131 int minx, maxx, miny, maxy;
135 /* Macro that executes 'block' once per light in lld, including
136 * the origin if include_origin is specified. 'block' can use
137 * lx and ly as the coords. */
138 #define FOREACHLIT(lld,block) do { \
141 for (lx = (lld)->minx; lx <= (lld)->maxx; lx++) { \
142 if (lx == (lld)->ox) continue; \
146 for (ly = (lld)->miny; ly <= (lld)->maxy; ly++) { \
147 if (!(lld)->include_origin && ly == (lld)->oy) continue; \
154 struct { int x, y; unsigned int f; } points[4];
158 /* Fills in (doesn't allocate) a surrounds structure with the grid locations
159 * around a given square, taking account of the edges. */
160 static void get_surrounds(game_state *state, int ox, int oy, surrounds *s)
162 assert(ox >= 0 && ox < state->w && oy >= 0 && oy < state->h);
164 #define ADDPOINT(cond,nx,ny) do {\
166 s->points[s->npoints].x = (nx); \
167 s->points[s->npoints].y = (ny); \
168 s->points[s->npoints].f = 0; \
171 ADDPOINT(ox > 0, ox-1, oy);
172 ADDPOINT(ox < (state->w-1), ox+1, oy);
173 ADDPOINT(oy > 0, ox, oy-1);
174 ADDPOINT(oy < (state->h-1), ox, oy+1);
177 /* --- Game parameter functions --- */
179 #define DEFAULT_PRESET 0
181 const struct game_params lightup_presets[] = {
182 { 7, 7, 20, SYMM_ROT4, 0 },
183 { 7, 7, 20, SYMM_ROT4, 1 },
184 { 7, 7, 20, SYMM_ROT4, 2 },
185 { 10, 10, 20, SYMM_ROT2, 0 },
186 { 10, 10, 20, SYMM_ROT2, 1 },
188 { 12, 12, 20, SYMM_ROT2, 0 },
189 { 12, 12, 20, SYMM_ROT2, 1 },
191 { 10, 10, 20, SYMM_ROT2, 2 },
192 { 14, 14, 20, SYMM_ROT2, 0 },
193 { 14, 14, 20, SYMM_ROT2, 1 },
194 { 14, 14, 20, SYMM_ROT2, 2 }
198 static game_params *default_params(void)
200 game_params *ret = snew(game_params);
201 *ret = lightup_presets[DEFAULT_PRESET];
206 static int game_fetch_preset(int i, char **name, game_params **params)
211 if (i < 0 || i >= lenof(lightup_presets))
214 ret = default_params();
215 *ret = lightup_presets[i];
218 sprintf(buf, "%dx%d %s",
220 ret->difficulty == 2 ? "hard" :
221 ret->difficulty == 1 ? "tricky" : "easy");
227 static void free_params(game_params *params)
232 static game_params *dup_params(game_params *params)
234 game_params *ret = snew(game_params);
235 *ret = *params; /* structure copy */
239 #define EATNUM(x) do { \
240 (x) = atoi(string); \
241 while (*string && isdigit((unsigned char)*string)) string++; \
244 static void decode_params(game_params *params, char const *string)
247 if (*string == 'x') {
251 if (*string == 'b') {
253 EATNUM(params->blackpc);
255 if (*string == 's') {
257 EATNUM(params->symm);
259 /* cope with user input such as '18x10' by ensuring symmetry
260 * is not selected by default to be incompatible with dimensions */
261 if (params->symm == SYMM_ROT4 && params->w != params->h)
262 params->symm = SYMM_ROT2;
264 params->difficulty = 0;
265 /* cope with old params */
266 if (*string == 'r') {
267 params->difficulty = 2;
270 if (*string == 'd') {
272 EATNUM(params->difficulty);
276 static char *encode_params(game_params *params, int full)
281 sprintf(buf, "%dx%db%ds%dd%d",
282 params->w, params->h, params->blackpc,
286 sprintf(buf, "%dx%d", params->w, params->h);
291 static config_item *game_configure(game_params *params)
296 ret = snewn(6, config_item);
298 ret[0].name = "Width";
299 ret[0].type = C_STRING;
300 sprintf(buf, "%d", params->w);
301 ret[0].sval = dupstr(buf);
304 ret[1].name = "Height";
305 ret[1].type = C_STRING;
306 sprintf(buf, "%d", params->h);
307 ret[1].sval = dupstr(buf);
310 ret[2].name = "%age of black squares";
311 ret[2].type = C_STRING;
312 sprintf(buf, "%d", params->blackpc);
313 ret[2].sval = dupstr(buf);
316 ret[3].name = "Symmetry";
317 ret[3].type = C_CHOICES;
318 ret[3].sval = ":None"
319 ":2-way mirror:2-way rotational"
320 ":4-way mirror:4-way rotational";
321 ret[3].ival = params->symm;
323 ret[4].name = "Difficulty";
324 ret[4].type = C_CHOICES;
325 ret[4].sval = ":Easy:Tricky:Hard";
326 ret[4].ival = params->difficulty;
336 static game_params *custom_params(config_item *cfg)
338 game_params *ret = snew(game_params);
340 ret->w = atoi(cfg[0].sval);
341 ret->h = atoi(cfg[1].sval);
342 ret->blackpc = atoi(cfg[2].sval);
343 ret->symm = cfg[3].ival;
344 ret->difficulty = cfg[4].ival;
349 static char *validate_params(game_params *params, int full)
351 if (params->w < 2 || params->h < 2)
352 return "Width and height must be at least 2";
354 if (params->blackpc < 5 || params->blackpc > 100)
355 return "Percentage of black squares must be between 5% and 100%";
356 if (params->w != params->h) {
357 if (params->symm == SYMM_ROT4)
358 return "4-fold symmetry is only available with square grids";
360 if (params->symm < 0 || params->symm >= SYMM_MAX)
361 return "Unknown symmetry type";
362 if (params->difficulty < 0 || params->difficulty > DIFFCOUNT)
363 return "Unknown difficulty level";
368 /* --- Game state construction/freeing helper functions --- */
370 static game_state *new_state(game_params *params)
372 game_state *ret = snew(game_state);
376 ret->lights = snewn(ret->w * ret->h, int);
378 memset(ret->lights, 0, ret->w * ret->h * sizeof(int));
379 ret->flags = snewn(ret->w * ret->h, unsigned int);
380 memset(ret->flags, 0, ret->w * ret->h * sizeof(unsigned int));
381 ret->completed = ret->used_solve = 0;
385 static game_state *dup_game(game_state *state)
387 game_state *ret = snew(game_state);
392 ret->lights = snewn(ret->w * ret->h, int);
393 memcpy(ret->lights, state->lights, ret->w * ret->h * sizeof(int));
394 ret->nlights = state->nlights;
396 ret->flags = snewn(ret->w * ret->h, unsigned int);
397 memcpy(ret->flags, state->flags, ret->w * ret->h * sizeof(unsigned int));
399 ret->completed = state->completed;
400 ret->used_solve = state->used_solve;
405 static void free_game(game_state *state)
407 sfree(state->lights);
412 static void debug_state(game_state *state)
417 for (y = 0; y < state->h; y++) {
418 for (x = 0; x < state->w; x++) {
420 if (GRID(state, flags, x, y) & F_BLACK) {
421 if (GRID(state, flags, x, y) & F_NUMBERED)
422 c = GRID(state, lights, x, y) + '0';
426 if (GRID(state, flags, x, y) & F_LIGHT)
428 else if (GRID(state, flags, x, y) & F_IMPOSSIBLE)
431 debug(("%c", (int)c));
434 for (x = 0; x < state->w; x++) {
435 if (GRID(state, flags, x, y) & F_BLACK)
438 c = (GRID(state, flags, x, y) & F_LIGHT) ? 'A' : 'a';
439 c += GRID(state, lights, x, y);
441 debug(("%c", (int)c));
447 /* --- Game completion test routines. --- */
449 /* These are split up because occasionally functions are only
450 * interested in one particular aspect. */
452 /* Returns non-zero if all grid spaces are lit. */
453 static int grid_lit(game_state *state)
457 for (x = 0; x < state->w; x++) {
458 for (y = 0; y < state->h; y++) {
459 if (GRID(state,flags,x,y) & F_BLACK) continue;
460 if (GRID(state,lights,x,y) == 0)
467 /* Returns non-zero if any lights are lit by other lights. */
468 static int grid_overlap(game_state *state)
472 for (x = 0; x < state->w; x++) {
473 for (y = 0; y < state->h; y++) {
474 if (!(GRID(state, flags, x, y) & F_LIGHT)) continue;
475 if (GRID(state, lights, x, y) > 1)
482 static int number_wrong(game_state *state, int x, int y)
485 int i, n, empty, lights = GRID(state, lights, x, y);
488 * This function computes the display hint for a number: we
489 * turn the number red if it is definitely wrong. This means
492 * (a) it has too many lights around it, or
493 * (b) it would have too few lights around it even if all the
494 * plausible squares (not black, lit or F_IMPOSSIBLE) were
495 * filled with lights.
498 assert(GRID(state, flags, x, y) & F_NUMBERED);
499 get_surrounds(state, x, y, &s);
502 for (i = 0; i < s.npoints; i++) {
503 if (GRID(state,flags,s.points[i].x,s.points[i].y) & F_LIGHT) {
507 if (GRID(state,flags,s.points[i].x,s.points[i].y) & F_BLACK)
509 if (GRID(state,flags,s.points[i].x,s.points[i].y) & F_IMPOSSIBLE)
511 if (GRID(state,lights,s.points[i].x,s.points[i].y))
515 return (n > lights || (n + empty < lights));
518 static int number_correct(game_state *state, int x, int y)
521 int n = 0, i, lights = GRID(state, lights, x, y);
523 assert(GRID(state, flags, x, y) & F_NUMBERED);
524 get_surrounds(state, x, y, &s);
525 for (i = 0; i < s.npoints; i++) {
526 if (GRID(state,flags,s.points[i].x,s.points[i].y) & F_LIGHT)
529 return (n == lights) ? 1 : 0;
532 /* Returns non-zero if any numbers add up incorrectly. */
533 static int grid_addsup(game_state *state)
537 for (x = 0; x < state->w; x++) {
538 for (y = 0; y < state->h; y++) {
539 if (!(GRID(state, flags, x, y) & F_NUMBERED)) continue;
540 if (!number_correct(state, x, y)) return 0;
546 static int grid_correct(game_state *state)
548 if (grid_lit(state) &&
549 !grid_overlap(state) &&
550 grid_addsup(state)) return 1;
554 /* --- Board initial setup (blacks, lights, numbers) --- */
556 static void clean_board(game_state *state, int leave_blacks)
559 for (x = 0; x < state->w; x++) {
560 for (y = 0; y < state->h; y++) {
562 GRID(state, flags, x, y) &= F_BLACK;
564 GRID(state, flags, x, y) = 0;
565 GRID(state, lights, x, y) = 0;
571 static void set_blacks(game_state *state, game_params *params, random_state *rs)
573 int x, y, degree = 0, rotate = 0, nblack;
575 int wodd = (state->w % 2) ? 1 : 0;
576 int hodd = (state->h % 2) ? 1 : 0;
579 switch (params->symm) {
580 case SYMM_NONE: degree = 1; rotate = 0; break;
581 case SYMM_ROT2: degree = 2; rotate = 1; break;
582 case SYMM_REF2: degree = 2; rotate = 0; break;
583 case SYMM_ROT4: degree = 4; rotate = 1; break;
584 case SYMM_REF4: degree = 4; rotate = 0; break;
585 default: assert(!"Unknown symmetry type");
587 if (params->symm == SYMM_ROT4 && (state->h != state->w))
588 assert(!"4-fold symmetry unavailable without square grid");
593 if (!rotate) rw += wodd; /* ... but see below. */
595 } else if (degree == 2) {
604 /* clear, then randomise, required region. */
605 clean_board(state, 0);
606 nblack = (rw * rh * params->blackpc) / 100;
607 for (i = 0; i < nblack; i++) {
609 x = random_upto(rs,rw);
610 y = random_upto(rs,rh);
611 } while (GRID(state,flags,x,y) & F_BLACK);
612 GRID(state, flags, x, y) |= F_BLACK;
615 /* Copy required region. */
616 if (params->symm == SYMM_NONE) return;
618 for (x = 0; x < rw; x++) {
619 for (y = 0; y < rh; y++) {
623 xs[1] = state->w - 1 - (rotate ? y : x);
624 ys[1] = rotate ? x : y;
625 xs[2] = rotate ? (state->w - 1 - x) : x;
626 ys[2] = state->h - 1 - y;
627 xs[3] = rotate ? y : (state->w - 1 - x);
628 ys[3] = state->h - 1 - (rotate ? x : y);
632 xs[1] = rotate ? (state->w - 1 - x) : x;
633 ys[1] = state->h - 1 - y;
635 for (i = 1; i < degree; i++) {
636 GRID(state, flags, xs[i], ys[i]) =
637 GRID(state, flags, xs[0], ys[0]);
641 /* SYMM_ROT4 misses the middle square above; fix that here. */
642 if (degree == 4 && rotate && wodd &&
643 (random_upto(rs,100) <= (unsigned int)params->blackpc))
645 state->w/2 + wodd - 1, state->h/2 + hodd - 1) |= F_BLACK;
647 #ifdef SOLVER_DIAGNOSTICS
648 if (verbose) debug_state(state);
652 /* Fills in (does not allocate) a ll_data with all the tiles that would
653 * be illuminated by a light at point (ox,oy). If origin=1 then the
654 * origin is included in this list. */
655 static void list_lights(game_state *state, int ox, int oy, int origin,
660 lld->ox = lld->minx = lld->maxx = ox;
661 lld->oy = lld->miny = lld->maxy = oy;
662 lld->include_origin = origin;
665 for (x = ox-1; x >= 0; x--) {
666 if (GRID(state, flags, x, y) & F_BLACK) break;
667 if (x < lld->minx) lld->minx = x;
669 for (x = ox+1; x < state->w; x++) {
670 if (GRID(state, flags, x, y) & F_BLACK) break;
671 if (x > lld->maxx) lld->maxx = x;
675 for (y = oy-1; y >= 0; y--) {
676 if (GRID(state, flags, x, y) & F_BLACK) break;
677 if (y < lld->miny) lld->miny = y;
679 for (y = oy+1; y < state->h; y++) {
680 if (GRID(state, flags, x, y) & F_BLACK) break;
681 if (y > lld->maxy) lld->maxy = y;
685 /* Makes sure a light is the given state, editing the lights table to suit the
686 * new state if necessary. */
687 static void set_light(game_state *state, int ox, int oy, int on)
692 assert(!(GRID(state,flags,ox,oy) & F_BLACK));
694 if (!on && GRID(state,flags,ox,oy) & F_LIGHT) {
696 GRID(state,flags,ox,oy) &= ~F_LIGHT;
698 } else if (on && !(GRID(state,flags,ox,oy) & F_LIGHT)) {
700 GRID(state,flags,ox,oy) |= F_LIGHT;
705 list_lights(state,ox,oy,1,&lld);
706 FOREACHLIT(&lld, GRID(state,lights,lx,ly) += diff; );
710 /* Returns 1 if removing a light at (x,y) would cause a square to go dark. */
711 static int check_dark(game_state *state, int x, int y)
715 list_lights(state, x, y, 1, &lld);
716 FOREACHLIT(&lld, if (GRID(state,lights,lx,ly) == 1) { return 1; } );
720 /* Sets up an initial random correct position (i.e. every
721 * space lit, and no lights lit by other lights) by filling the
722 * grid with lights and then removing lights one by one at random. */
723 static void place_lights(game_state *state, random_state *rs)
725 int i, x, y, n, *numindices, wh = state->w*state->h;
728 numindices = snewn(wh, int);
729 for (i = 0; i < wh; i++) numindices[i] = i;
730 shuffle(numindices, wh, sizeof(*numindices), rs);
732 /* Place a light on all grid squares without lights. */
733 for (x = 0; x < state->w; x++) {
734 for (y = 0; y < state->h; y++) {
735 GRID(state, flags, x, y) &= ~F_MARK; /* we use this later. */
736 if (GRID(state, flags, x, y) & F_BLACK) continue;
737 set_light(state, x, y, 1);
741 for (i = 0; i < wh; i++) {
742 y = numindices[i] / state->w;
743 x = numindices[i] % state->w;
744 if (!(GRID(state, flags, x, y) & F_LIGHT)) continue;
745 if (GRID(state, flags, x, y) & F_MARK) continue;
746 list_lights(state, x, y, 0, &lld);
748 /* If we're not lighting any lights ourself, don't remove anything. */
750 FOREACHLIT(&lld, if (GRID(state,flags,lx,ly) & F_LIGHT) { n += 1; } );
751 if (n == 0) continue; /* [1] */
753 /* Check whether removing lights we're lighting would cause anything
756 FOREACHLIT(&lld, if (GRID(state,flags,lx,ly) & F_LIGHT) { n += check_dark(state,lx,ly); } );
758 /* No, it wouldn't, so we can remove them all. */
759 FOREACHLIT(&lld, set_light(state,lx,ly, 0); );
760 GRID(state,flags,x,y) |= F_MARK;
763 if (!grid_overlap(state)) {
765 return; /* we're done. */
767 assert(grid_lit(state));
769 /* could get here if the line at [1] continue'd out of the loop. */
770 if (grid_overlap(state)) {
772 assert(!"place_lights failed to resolve overlapping lights!");
777 /* Fills in all black squares with numbers of adjacent lights. */
778 static void place_numbers(game_state *state)
783 for (x = 0; x < state->w; x++) {
784 for (y = 0; y < state->h; y++) {
785 if (!(GRID(state,flags,x,y) & F_BLACK)) continue;
786 get_surrounds(state, x, y, &s);
788 for (i = 0; i < s.npoints; i++) {
789 if (GRID(state,flags,s.points[i].x, s.points[i].y) & F_LIGHT)
792 GRID(state,flags,x,y) |= F_NUMBERED;
793 GRID(state,lights,x,y) = n;
798 /* --- Actual solver, with helper subroutines. --- */
800 static void tsl_callback(game_state *state,
801 int lx, int ly, int *x, int *y, int *n)
803 if (GRID(state,flags,lx,ly) & F_IMPOSSIBLE) return;
804 if (GRID(state,lights,lx,ly) > 0) return;
805 *x = lx; *y = ly; (*n)++;
808 static int try_solve_light(game_state *state, int ox, int oy,
809 unsigned int flags, int lights)
812 int sx = 0, sy = 0, n = 0;
814 if (lights > 0) return 0;
815 if (flags & F_BLACK) return 0;
817 /* We have an unlit square; count how many ways there are left to
818 * place a light that lights us (including this square); if only
819 * one, we must put a light there. Squares that could light us
820 * are, of course, the same as the squares we would light... */
821 list_lights(state, ox, oy, 1, &lld);
822 FOREACHLIT(&lld, { tsl_callback(state, lx, ly, &sx, &sy, &n); });
824 set_light(state, sx, sy, 1);
825 #ifdef SOLVER_DIAGNOSTICS
826 debug(("(%d,%d) can only be lit from (%d,%d); setting to LIGHT\n",
828 if (verbose) debug_state(state);
836 static int could_place_light(unsigned int flags, int lights)
838 if (flags & (F_BLACK | F_IMPOSSIBLE)) return 0;
839 return (lights > 0) ? 0 : 1;
842 static int could_place_light_xy(game_state *state, int x, int y)
844 int lights = GRID(state,lights,x,y);
845 unsigned int flags = GRID(state,flags,x,y);
846 return (could_place_light(flags, lights)) ? 1 : 0;
849 /* For a given number square, determine whether we have enough info
850 * to unambiguously place its lights. */
851 static int try_solve_number(game_state *state, int nx, int ny,
852 unsigned int nflags, int nlights)
855 int x, y, nl, ns, i, ret = 0, lights;
858 if (!(nflags & F_NUMBERED)) return 0;
860 get_surrounds(state,nx,ny,&s);
863 /* nl is no. of lights we need to place, ns is no. of spaces we
864 * have to place them in. Try and narrow these down, and mark
865 * points we can ignore later. */
866 for (i = 0; i < s.npoints; i++) {
867 x = s.points[i].x; y = s.points[i].y;
868 flags = GRID(state,flags,x,y);
869 lights = GRID(state,lights,x,y);
870 if (flags & F_LIGHT) {
871 /* light here already; one less light for one less place. */
873 s.points[i].f |= F_MARK;
874 } else if (!could_place_light(flags, lights)) {
876 s.points[i].f |= F_MARK;
879 if (ns == 0) return 0; /* nowhere to put anything. */
881 /* we have placed all lights we need to around here; all remaining
882 * surrounds are therefore IMPOSSIBLE. */
883 GRID(state,flags,nx,ny) |= F_NUMBERUSED;
884 for (i = 0; i < s.npoints; i++) {
885 if (!(s.points[i].f & F_MARK)) {
886 GRID(state,flags,s.points[i].x,s.points[i].y) |= F_IMPOSSIBLE;
890 #ifdef SOLVER_DIAGNOSTICS
891 printf("Clue at (%d,%d) full; setting unlit to IMPOSSIBLE.\n",
893 if (verbose) debug_state(state);
895 } else if (nl == ns) {
896 /* we have as many lights to place as spaces; fill them all. */
897 GRID(state,flags,nx,ny) |= F_NUMBERUSED;
898 for (i = 0; i < s.npoints; i++) {
899 if (!(s.points[i].f & F_MARK)) {
900 set_light(state, s.points[i].x,s.points[i].y, 1);
904 #ifdef SOLVER_DIAGNOSTICS
905 printf("Clue at (%d,%d) trivial; setting unlit to LIGHT.\n",
907 if (verbose) debug_state(state);
918 #define SCRATCHSZ (state->w+state->h)
920 /* New solver algorithm: overlapping sets can add IMPOSSIBLE flags.
921 * Algorithm thanks to Simon:
923 * (a) Any square where you can place a light has a set of squares
924 * which would become non-lights as a result. (This includes
925 * squares lit by the first square, and can also include squares
926 * adjacent to the same clue square if the new light is the last
927 * one around that clue.) Call this MAKESDARK(x,y) with (x,y) being
928 * the square you place a light.
930 * (b) Any unlit square has a set of squares on which you could place
931 * a light to illuminate it. (Possibly including itself, of
932 * course.) This set of squares has the property that _at least
933 * one_ of them must contain a light. Sets of this type also arise
934 * from clue squares. Call this MAKESLIGHT(x,y), again with (x,y)
935 * the square you would place a light.
937 * (c) If there exists (dx,dy) and (lx,ly) such that MAKESDARK(dx,dy) is
938 * a superset of MAKESLIGHT(lx,ly), this implies that placing a light at
939 * (dx,dy) would either leave no remaining way to illuminate a certain
940 * square, or would leave no remaining way to fulfill a certain clue
941 * (at lx,ly). In either case, a light can be ruled out at that position.
943 * So, we construct all possible MAKESLIGHT sets, both from unlit squares
944 * and clue squares, and then we look for plausible MAKESDARK sets that include
945 * our (lx,ly) to see if we can find a (dx,dy) to rule out. By the time we have
946 * constructed the MAKESLIGHT set we don't care about (lx,ly), just the set
949 * Once we have such a set, Simon came up with a Cunning Plan to find
950 * the most sensible MAKESDARK candidate:
952 * (a) for each square S in your set X, find all the squares which _would_
953 * rule it out. That means any square which would light S, plus
954 * any square adjacent to the same clue square as S (provided
955 * that clue square has only one remaining light to be placed).
956 * It's not hard to make this list. Don't do anything with this
957 * data at the moment except _count_ the squares.
959 * (b) Find the square S_min in the original set which has the
960 * _smallest_ number of other squares which would rule it out.
962 * (c) Find all the squares that rule out S_min (it's probably
963 * better to recompute this than to have stored it during step
964 * (a), since the CPU requirement is modest but the storage
965 * cost would get ugly.) For each of these squares, see if it
966 * rules out everything else in the set X. Any which does can
967 * be marked as not-a-light.
971 typedef void (*trl_cb)(game_state *state, int dx, int dy,
972 struct setscratch *scratch, int n, void *ctx);
974 static void try_rule_out(game_state *state, int x, int y,
975 struct setscratch *scratch, int n,
976 trl_cb cb, void *ctx);
978 static void trl_callback_search(game_state *state, int dx, int dy,
979 struct setscratch *scratch, int n, void *ignored)
983 #ifdef SOLVER_DIAGNOSTICS
984 if (verbose) debug(("discount cb: light at (%d,%d)\n", dx, dy));
987 for (i = 0; i < n; i++) {
988 if (dx == scratch[i].x && dy == scratch[i].y) {
995 static void trl_callback_discount(game_state *state, int dx, int dy,
996 struct setscratch *scratch, int n, void *ctx)
998 int *didsth = (int *)ctx;
1001 if (GRID(state,flags,dx,dy) & F_IMPOSSIBLE) {
1002 #ifdef SOLVER_DIAGNOSTICS
1003 debug(("Square at (%d,%d) already impossible.\n", dx,dy));
1008 /* Check whether a light at (dx,dy) rules out everything
1009 * in scratch, and mark (dx,dy) as IMPOSSIBLE if it does.
1010 * We can use try_rule_out for this as well, as the set of
1011 * squares which would rule out (x,y) is the same as the
1012 * set of squares which (x,y) would rule out. */
1014 #ifdef SOLVER_DIAGNOSTICS
1015 if (verbose) debug(("Checking whether light at (%d,%d) rules out everything in scratch.\n", dx, dy));
1018 for (i = 0; i < n; i++)
1020 try_rule_out(state, dx, dy, scratch, n, trl_callback_search, NULL);
1021 for (i = 0; i < n; i++) {
1022 if (scratch[i].n == 0) return;
1024 /* The light ruled out everything in scratch. Yay. */
1025 GRID(state,flags,dx,dy) |= F_IMPOSSIBLE;
1026 #ifdef SOLVER_DIAGNOSTICS
1027 debug(("Set reduction discounted square at (%d,%d):\n", dx,dy));
1028 if (verbose) debug_state(state);
1034 static void trl_callback_incn(game_state *state, int dx, int dy,
1035 struct setscratch *scratch, int n, void *ctx)
1037 struct setscratch *s = (struct setscratch *)ctx;
1041 static void try_rule_out(game_state *state, int x, int y,
1042 struct setscratch *scratch, int n,
1043 trl_cb cb, void *ctx)
1045 /* XXX Find all the squares which would rule out (x,y); anything
1046 * that would light it as well as squares adjacent to same clues
1047 * as X assuming that clue only has one remaining light.
1048 * Call the callback with each square. */
1051 int i, j, curr_lights, tot_lights;
1053 /* Find all squares that would rule out a light at (x,y) and call trl_cb
1054 * with them: anything that would light (x,y)... */
1056 list_lights(state, x, y, 0, &lld);
1057 FOREACHLIT(&lld, { if (could_place_light_xy(state, lx, ly)) { cb(state, lx, ly, scratch, n, ctx); } });
1059 /* ... as well as any empty space (that isn't x,y) next to any clue square
1060 * next to (x,y) that only has one light left to place. */
1062 get_surrounds(state, x, y, &s);
1063 for (i = 0; i < s.npoints; i++) {
1064 if (!(GRID(state,flags,s.points[i].x,s.points[i].y) & F_NUMBERED))
1066 /* we have an adjacent clue square; find /its/ surrounds
1067 * and count the remaining lights it needs. */
1068 get_surrounds(state,s.points[i].x,s.points[i].y,&ss);
1070 for (j = 0; j < ss.npoints; j++) {
1071 if (GRID(state,flags,ss.points[j].x,ss.points[j].y) & F_LIGHT)
1074 tot_lights = GRID(state, lights, s.points[i].x, s.points[i].y);
1075 /* We have a clue with tot_lights to fill, and curr_lights currently
1076 * around it. If adding a light at (x,y) fills up the clue (i.e.
1077 * curr_lights + 1 = tot_lights) then we need to discount all other
1078 * unlit squares around the clue. */
1079 if ((curr_lights + 1) == tot_lights) {
1080 for (j = 0; j < ss.npoints; j++) {
1081 int lx = ss.points[j].x, ly = ss.points[j].y;
1082 if (lx == x && ly == y) continue;
1083 if (could_place_light_xy(state, lx, ly))
1084 cb(state, lx, ly, scratch, n, ctx);
1090 #ifdef SOLVER_DIAGNOSTICS
1091 static void debug_scratch(const char *msg, struct setscratch *scratch, int n)
1094 debug(("%s scratch (%d elements):\n", msg, n));
1095 for (i = 0; i < n; i++) {
1096 debug((" (%d,%d) n%d\n", scratch[i].x, scratch[i].y, scratch[i].n));
1101 static int discount_set(game_state *state,
1102 struct setscratch *scratch, int n)
1104 int i, besti, bestn, didsth = 0;
1106 #ifdef SOLVER_DIAGNOSTICS
1107 if (verbose > 1) debug_scratch("discount_set", scratch, n);
1109 if (n == 0) return 0;
1111 for (i = 0; i < n; i++) {
1112 try_rule_out(state, scratch[i].x, scratch[i].y, scratch, n,
1113 trl_callback_incn, (void*)&(scratch[i]));
1115 #ifdef SOLVER_DIAGNOSTICS
1116 if (verbose > 1) debug_scratch("discount_set after count", scratch, n);
1119 besti = -1; bestn = SCRATCHSZ;
1120 for (i = 0; i < n; i++) {
1121 if (scratch[i].n < bestn) {
1122 bestn = scratch[i].n;
1126 #ifdef SOLVER_DIAGNOSTICS
1127 if (verbose > 1) debug(("best square (%d,%d) with n%d.\n",
1128 scratch[besti].x, scratch[besti].y, scratch[besti].n));
1130 try_rule_out(state, scratch[besti].x, scratch[besti].y, scratch, n,
1131 trl_callback_discount, (void*)&didsth);
1132 #ifdef SOLVER_DIAGNOSTICS
1133 if (didsth) debug((" [from square (%d,%d)]\n",
1134 scratch[besti].x, scratch[besti].y));
1140 static void discount_clear(game_state *state, struct setscratch *scratch, int *n)
1143 memset(scratch, 0, SCRATCHSZ * sizeof(struct setscratch));
1146 static void unlit_cb(game_state *state, int lx, int ly,
1147 struct setscratch *scratch, int *n)
1149 if (could_place_light_xy(state, lx, ly)) {
1150 scratch[*n].x = lx; scratch[*n].y = ly; (*n)++;
1154 /* Construct a MAKESLIGHT set from an unlit square. */
1155 static int discount_unlit(game_state *state, int x, int y,
1156 struct setscratch *scratch)
1161 #ifdef SOLVER_DIAGNOSTICS
1162 if (verbose) debug(("Trying to discount for unlit square at (%d,%d).\n", x, y));
1163 if (verbose > 1) debug_state(state);
1166 discount_clear(state, scratch, &n);
1168 list_lights(state, x, y, 1, &lld);
1169 FOREACHLIT(&lld, { unlit_cb(state, lx, ly, scratch, &n); });
1170 didsth = discount_set(state, scratch, n);
1171 #ifdef SOLVER_DIAGNOSTICS
1172 if (didsth) debug((" [from unlit square at (%d,%d)].\n", x, y));
1178 /* Construct a series of MAKESLIGHT sets from a clue square.
1179 * for a clue square with N remaining spaces that must contain M lights, every
1180 * subset of size N-M+1 of those N spaces forms such a set.
1183 static int discount_clue(game_state *state, int x, int y,
1184 struct setscratch *scratch)
1186 int slen, m = GRID(state, lights, x, y), n, i, didsth = 0, lights;
1188 surrounds s, sempty;
1191 if (m == 0) return 0;
1193 #ifdef SOLVER_DIAGNOSTICS
1194 if (verbose) debug(("Trying to discount for sets at clue (%d,%d).\n", x, y));
1195 if (verbose > 1) debug_state(state);
1198 /* m is no. of lights still to place; starts off at the clue value
1199 * and decreases when we find a light already down.
1200 * n is no. of spaces left; starts off at 0 and goes up when we find
1201 * a plausible space. */
1203 get_surrounds(state, x, y, &s);
1204 memset(&sempty, 0, sizeof(surrounds));
1205 for (i = 0; i < s.npoints; i++) {
1206 int lx = s.points[i].x, ly = s.points[i].y;
1207 flags = GRID(state,flags,lx,ly);
1208 lights = GRID(state,lights,lx,ly);
1210 if (flags & F_LIGHT) m--;
1212 if (could_place_light(flags, lights)) {
1213 sempty.points[sempty.npoints].x = lx;
1214 sempty.points[sempty.npoints].y = ly;
1218 n = sempty.npoints; /* sempty is now a surrounds of only blank squares. */
1219 if (n == 0) return 0; /* clue is full already. */
1221 if (m < 0 || m > n) return 0; /* become impossible. */
1223 combi = new_combi(n - m + 1, n);
1224 while (next_combi(combi)) {
1225 discount_clear(state, scratch, &slen);
1226 for (i = 0; i < combi->r; i++) {
1227 scratch[slen].x = sempty.points[combi->a[i]].x;
1228 scratch[slen].y = sempty.points[combi->a[i]].y;
1231 if (discount_set(state, scratch, slen)) didsth = 1;
1234 #ifdef SOLVER_DIAGNOSTICS
1235 if (didsth) debug((" [from clue at (%d,%d)].\n", x, y));
1240 #define F_SOLVE_FORCEUNIQUE 1
1241 #define F_SOLVE_DISCOUNTSETS 2
1242 #define F_SOLVE_ALLOWRECURSE 4
1244 static unsigned int flags_from_difficulty(int difficulty)
1246 unsigned int sflags = F_SOLVE_FORCEUNIQUE;
1247 assert(difficulty <= DIFFCOUNT);
1248 if (difficulty >= 1) sflags |= F_SOLVE_DISCOUNTSETS;
1249 if (difficulty >= 2) sflags |= F_SOLVE_ALLOWRECURSE;
1253 #define MAXRECURSE 5
1255 static int solve_sub(game_state *state,
1256 unsigned int solve_flags, int depth,
1260 int x, y, didstuff, ncanplace, lights;
1261 int bestx, besty, n, bestn, copy_soluble, self_soluble, ret, maxrecurse = 0;
1264 struct setscratch *sscratch = NULL;
1266 #ifdef SOLVER_DIAGNOSTICS
1267 printf("solve_sub: depth = %d\n", depth);
1269 if (maxdepth && *maxdepth < depth) *maxdepth = depth;
1270 if (solve_flags & F_SOLVE_ALLOWRECURSE) maxrecurse = MAXRECURSE;
1273 if (grid_overlap(state)) {
1274 /* Our own solver, from scratch, should never cause this to happen
1275 * (assuming a soluble grid). However, if we're trying to solve
1276 * from a half-completed *incorrect* grid this might occur; we
1277 * just return the 'no solutions' code in this case. */
1281 if (grid_correct(state)) { ret = 1; goto done; }
1285 /* These 2 loops, and the functions they call, are the critical loops
1286 * for timing; any optimisations should look here first. */
1287 for (x = 0; x < state->w; x++) {
1288 for (y = 0; y < state->h; y++) {
1289 flags = GRID(state,flags,x,y);
1290 lights = GRID(state,lights,x,y);
1291 ncanplace += could_place_light(flags, lights);
1293 if (try_solve_light(state, x, y, flags, lights)) didstuff = 1;
1294 if (try_solve_number(state, x, y, flags, lights)) didstuff = 1;
1297 if (didstuff) continue;
1299 /* nowhere to put a light, puzzle is unsoluble. */
1303 if (solve_flags & F_SOLVE_DISCOUNTSETS) {
1304 if (!sscratch) sscratch = snewn(SCRATCHSZ, struct setscratch);
1305 /* Try a more cunning (and more involved) way... more details above. */
1306 for (x = 0; x < state->w; x++) {
1307 for (y = 0; y < state->h; y++) {
1308 flags = GRID(state,flags,x,y);
1309 lights = GRID(state,lights,x,y);
1311 if (!(flags & F_BLACK) && lights == 0) {
1312 if (discount_unlit(state, x, y, sscratch)) {
1314 goto reduction_success;
1316 } else if (flags & F_NUMBERED) {
1317 if (discount_clue(state, x, y, sscratch)) {
1319 goto reduction_success;
1326 if (didstuff) continue;
1328 /* We now have to make a guess; we have places to put lights but
1329 * no definite idea about where they can go. */
1330 if (depth >= maxrecurse) {
1331 /* mustn't delve any deeper. */
1332 ret = -1; goto done;
1334 /* Of all the squares that we could place a light, pick the one
1335 * that would light the most currently unlit squares. */
1336 /* This heuristic was just plucked from the air; there may well be
1337 * a more efficient way of choosing a square to flip to minimise
1340 bestx = besty = -1; /* suyb */
1341 for (x = 0; x < state->w; x++) {
1342 for (y = 0; y < state->h; y++) {
1343 flags = GRID(state,flags,x,y);
1344 lights = GRID(state,lights,x,y);
1345 if (!could_place_light(flags, lights)) continue;
1348 list_lights(state, x, y, 1, &lld);
1349 FOREACHLIT(&lld, { if (GRID(state,lights,lx,ly) == 0) n++; });
1351 bestn = n; bestx = x; besty = y;
1356 assert(bestx >= 0 && besty >= 0);
1358 /* Now we've chosen a plausible (x,y), try to solve it once as 'lit'
1359 * and once as 'impossible'; we need to make one copy to do this. */
1361 scopy = dup_game(state);
1362 #ifdef SOLVER_DIAGNOSTICS
1363 debug(("Recursing #1: trying (%d,%d) as IMPOSSIBLE\n", bestx, besty));
1365 GRID(state,flags,bestx,besty) |= F_IMPOSSIBLE;
1366 self_soluble = solve_sub(state, solve_flags, depth+1, maxdepth);
1368 if (!(solve_flags & F_SOLVE_FORCEUNIQUE) && self_soluble > 0) {
1369 /* we didn't care about finding all solutions, and we just
1370 * found one; return with it immediately. */
1376 #ifdef SOLVER_DIAGNOSTICS
1377 debug(("Recursing #2: trying (%d,%d) as LIGHT\n", bestx, besty));
1379 set_light(scopy, bestx, besty, 1);
1380 copy_soluble = solve_sub(scopy, solve_flags, depth+1, maxdepth);
1382 /* If we wanted a unique solution but we hit our recursion limit
1383 * (on either branch) then we have to assume we didn't find possible
1384 * extra solutions, and return 'not soluble'. */
1385 if ((solve_flags & F_SOLVE_FORCEUNIQUE) &&
1386 ((copy_soluble < 0) || (self_soluble < 0))) {
1388 /* Make sure that whether or not it was self or copy (or both) that
1389 * were soluble, that we return a solved state in self. */
1390 } else if (copy_soluble <= 0) {
1391 /* copy wasn't soluble; keep self state and return that result. */
1393 } else if (self_soluble <= 0) {
1394 /* copy solved and we didn't, so copy in copy's (now solved)
1395 * flags and light state. */
1396 memcpy(state->lights, scopy->lights,
1397 scopy->w * scopy->h * sizeof(int));
1398 memcpy(state->flags, scopy->flags,
1399 scopy->w * scopy->h * sizeof(unsigned int));
1402 ret = copy_soluble + self_soluble;
1408 if (sscratch) sfree(sscratch);
1409 #ifdef SOLVER_DIAGNOSTICS
1411 debug(("solve_sub: depth = %d returning, ran out of recursion.\n",
1414 debug(("solve_sub: depth = %d returning, %d solutions.\n",
1420 /* Fills in the (possibly partially-complete) game_state as far as it can,
1421 * returning the number of possible solutions. If it returns >0 then the
1422 * game_state will be in a solved state, but you won't know which one. */
1423 static int dosolve(game_state *state, int solve_flags, int *maxdepth)
1427 for (x = 0; x < state->w; x++) {
1428 for (y = 0; y < state->h; y++) {
1429 GRID(state,flags,x,y) &= ~F_NUMBERUSED;
1432 nsol = solve_sub(state, solve_flags, 0, maxdepth);
1436 static int strip_unused_nums(game_state *state)
1439 for (x = 0; x < state->w; x++) {
1440 for (y = 0; y < state->h; y++) {
1441 if ((GRID(state,flags,x,y) & F_NUMBERED) &&
1442 !(GRID(state,flags,x,y) & F_NUMBERUSED)) {
1443 GRID(state,flags,x,y) &= ~F_NUMBERED;
1444 GRID(state,lights,x,y) = 0;
1449 debug(("Stripped %d unused numbers.\n", n));
1453 static void unplace_lights(game_state *state)
1456 for (x = 0; x < state->w; x++) {
1457 for (y = 0; y < state->h; y++) {
1458 if (GRID(state,flags,x,y) & F_LIGHT)
1459 set_light(state,x,y,0);
1460 GRID(state,flags,x,y) &= ~F_IMPOSSIBLE;
1461 GRID(state,flags,x,y) &= ~F_NUMBERUSED;
1466 static int puzzle_is_good(game_state *state, int difficulty)
1468 int nsol, mdepth = 0;
1469 unsigned int sflags = flags_from_difficulty(difficulty);
1471 unplace_lights(state);
1473 #ifdef SOLVER_DIAGNOSTICS
1474 debug(("Trying to solve with difficulty %d (0x%x):\n",
1475 difficulty, sflags));
1476 if (verbose) debug_state(state);
1479 nsol = dosolve(state, sflags, &mdepth);
1480 /* if we wanted an easy puzzle, make sure we didn't need recursion. */
1481 if (!(sflags & F_SOLVE_ALLOWRECURSE) && mdepth > 0) {
1482 debug(("Ignoring recursive puzzle.\n"));
1486 debug(("%d solutions found.\n", nsol));
1487 if (nsol <= 0) return 0;
1488 if (nsol > 1) return 0;
1492 /* --- New game creation and user input code. --- */
1494 /* The basic algorithm here is to generate the most complex grid possible
1495 * while honouring two restrictions:
1497 * * we require a unique solution, and
1498 * * either we require solubility with no recursion (!params->recurse)
1499 * * or we require some recursion. (params->recurse).
1501 * The solver helpfully keeps track of the numbers it needed to use to
1502 * get its solution, so we use that to remove an initial set of numbers
1503 * and check we still satsify our requirements (on uniqueness and
1504 * non-recursiveness, if applicable; we don't check explicit recursiveness
1507 * Then we try to remove all numbers in a random order, and see if we
1508 * still satisfy requirements (putting them back if we didn't).
1510 * Removing numbers will always, in general terms, make a puzzle require
1511 * more recursion but it may also mean a puzzle becomes non-unique.
1513 * Once we're done, if we wanted a recursive puzzle but the most difficult
1514 * puzzle we could come up with was non-recursive, we give up and try a new
1517 #define MAX_GRIDGEN_TRIES 20
1519 static char *new_game_desc(game_params *params, random_state *rs,
1520 char **aux, int interactive)
1522 game_state *news = new_state(params), *copys;
1523 int i, j, run, x, y, wh = params->w*params->h, num;
1527 /* Construct a shuffled list of grid positions; we only
1528 * do this once, because if it gets used more than once it'll
1529 * be on a different grid layout. */
1530 numindices = snewn(wh, int);
1531 for (j = 0; j < wh; j++) numindices[j] = j;
1532 shuffle(numindices, wh, sizeof(*numindices), rs);
1535 for (i = 0; i < MAX_GRIDGEN_TRIES; i++) {
1536 set_blacks(news, params, rs); /* also cleans board. */
1538 /* set up lights and then the numbers, and remove the lights */
1539 place_lights(news, rs);
1540 debug(("Generating initial grid.\n"));
1541 place_numbers(news);
1542 if (!puzzle_is_good(news, params->difficulty)) continue;
1544 /* Take a copy, remove numbers we didn't use and check there's
1545 * still a unique solution; if so, use the copy subsequently. */
1546 copys = dup_game(news);
1547 strip_unused_nums(copys);
1548 if (!puzzle_is_good(copys, params->difficulty)) {
1549 debug(("Stripped grid is not good, reverting.\n"));
1556 /* Go through grid removing numbers at random one-by-one and
1557 * trying to solve again; if it ceases to be good put the number back. */
1558 for (j = 0; j < wh; j++) {
1559 y = numindices[j] / params->w;
1560 x = numindices[j] % params->w;
1561 if (!(GRID(news, flags, x, y) & F_NUMBERED)) continue;
1562 num = GRID(news, lights, x, y);
1563 GRID(news, lights, x, y) = 0;
1564 GRID(news, flags, x, y) &= ~F_NUMBERED;
1565 if (!puzzle_is_good(news, params->difficulty)) {
1566 GRID(news, lights, x, y) = num;
1567 GRID(news, flags, x, y) |= F_NUMBERED;
1569 debug(("Removed (%d,%d) still soluble.\n", x, y));
1571 if (params->difficulty > 0) {
1572 /* Was the maximally-difficult puzzle difficult enough?
1573 * Check we can't solve it with a more simplistic solver. */
1574 if (puzzle_is_good(news, params->difficulty-1)) {
1575 debug(("Maximally-hard puzzle still not hard enough, skipping.\n"));
1582 /* Couldn't generate a good puzzle in however many goes. Ramp up the
1583 * %age of black squares (if we didn't already have lots; in which case
1584 * why couldn't we generate a puzzle?) and try again. */
1585 if (params->blackpc < 90) params->blackpc += 5;
1586 debug(("New black layout %d%%.\n", params->blackpc));
1589 /* Game is encoded as a long string one character per square;
1591 * 'B' is a black square with no number
1592 * '0', '1', '2', '3', '4' is a black square with a number. */
1593 ret = snewn((params->w * params->h) + 1, char);
1596 for (y = 0; y < params->h; y++) {
1597 for (x = 0; x < params->w; x++) {
1598 if (GRID(news,flags,x,y) & F_BLACK) {
1600 *p++ = ('a'-1) + run;
1603 if (GRID(news,flags,x,y) & F_NUMBERED)
1604 *p++ = '0' + GRID(news,lights,x,y);
1609 *p++ = ('a'-1) + run;
1617 *p++ = ('a'-1) + run;
1621 assert(p - ret <= params->w * params->h);
1628 static char *validate_desc(game_params *params, char *desc)
1631 for (i = 0; i < params->w*params->h; i++) {
1632 if (*desc >= '0' && *desc <= '4')
1634 else if (*desc == 'B')
1636 else if (*desc >= 'a' && *desc <= 'z')
1637 i += *desc - 'a'; /* and the i++ will add another one */
1639 return "Game description shorter than expected";
1641 return "Game description contained unexpected character";
1644 if (*desc || i > params->w*params->h)
1645 return "Game description longer than expected";
1650 static game_state *new_game(midend *me, game_params *params, char *desc)
1652 game_state *ret = new_state(params);
1656 for (y = 0; y < params->h; y++) {
1657 for (x = 0; x < params->w; x++) {
1663 if (c >= 'a' && c <= 'z')
1673 case '0': case '1': case '2': case '3': case '4':
1674 GRID(ret,flags,x,y) |= F_NUMBERED;
1675 GRID(ret,lights,x,y) = (c - '0');
1679 GRID(ret,flags,x,y) |= F_BLACK;
1687 assert(!"Malformed desc.");
1692 if (*desc) assert(!"Over-long desc.");
1697 static char *solve_game(game_state *state, game_state *currstate,
1698 char *aux, char **error)
1701 char *move = NULL, buf[80];
1702 int movelen, movesize, x, y, len;
1703 unsigned int oldflags, solvedflags, sflags;
1705 /* We don't care here about non-unique puzzles; if the
1706 * user entered one themself then I doubt they care. */
1708 sflags = F_SOLVE_ALLOWRECURSE | F_SOLVE_DISCOUNTSETS;
1710 /* Try and solve from where we are now (for non-unique
1711 * puzzles this may produce a different answer). */
1712 solved = dup_game(currstate);
1713 if (dosolve(solved, sflags, NULL) > 0) goto solved;
1716 /* That didn't work; try solving from the clean puzzle. */
1717 solved = dup_game(state);
1718 if (dosolve(solved, sflags, NULL) > 0) goto solved;
1719 *error = "Unable to find a solution to this puzzle.";
1724 move = snewn(movesize, char);
1726 move[movelen++] = 'S';
1727 move[movelen] = '\0';
1728 for (x = 0; x < currstate->w; x++) {
1729 for (y = 0; y < currstate->h; y++) {
1731 oldflags = GRID(currstate, flags, x, y);
1732 solvedflags = GRID(solved, flags, x, y);
1733 if ((oldflags & F_LIGHT) != (solvedflags & F_LIGHT))
1734 len = sprintf(buf, ";L%d,%d", x, y);
1735 else if ((oldflags & F_IMPOSSIBLE) != (solvedflags & F_IMPOSSIBLE))
1736 len = sprintf(buf, ";I%d,%d", x, y);
1738 if (movelen + len >= movesize) {
1739 movesize = movelen + len + 256;
1740 move = sresize(move, movesize, char);
1742 strcpy(move + movelen, buf);
1753 static int game_can_format_as_text_now(game_params *params)
1758 /* 'borrowed' from slant.c, mainly. I could have printed it one
1759 * character per cell (like debug_state) but that comes out tiny.
1760 * 'L' is used for 'light here' because 'O' looks too much like '0'
1761 * (black square with no surrounding lights). */
1762 static char *game_text_format(game_state *state)
1764 int w = state->w, h = state->h, W = w+1, H = h+1;
1765 int x, y, len, lights;
1769 len = (h+H) * (w+W+1) + 1;
1770 ret = snewn(len, char);
1773 for (y = 0; y < H; y++) {
1774 for (x = 0; x < W; x++) {
1781 for (x = 0; x < W; x++) {
1784 /* actual interesting bit. */
1785 flags = GRID(state, flags, x, y);
1786 lights = GRID(state, lights, x, y);
1787 if (flags & F_BLACK) {
1788 if (flags & F_NUMBERED)
1789 *p++ = '0' + lights;
1793 if (flags & F_LIGHT)
1795 else if (flags & F_IMPOSSIBLE)
1797 else if (lights > 0)
1809 assert(p - ret == len);
1814 int cur_x, cur_y, cur_visible;
1817 static game_ui *new_ui(game_state *state)
1819 game_ui *ui = snew(game_ui);
1820 ui->cur_x = ui->cur_y = ui->cur_visible = 0;
1824 static void free_ui(game_ui *ui)
1829 static char *encode_ui(game_ui *ui)
1831 /* nothing to encode. */
1835 static void decode_ui(game_ui *ui, char *encoding)
1837 /* nothing to decode. */
1840 static void game_changed_state(game_ui *ui, game_state *oldstate,
1841 game_state *newstate)
1843 if (newstate->completed)
1844 ui->cur_visible = 0;
1847 #define DF_BLACK 1 /* black square */
1848 #define DF_NUMBERED 2 /* black square with number */
1849 #define DF_LIT 4 /* display (white) square lit up */
1850 #define DF_LIGHT 8 /* display light in square */
1851 #define DF_OVERLAP 16 /* display light as overlapped */
1852 #define DF_CURSOR 32 /* display cursor */
1853 #define DF_NUMBERWRONG 64 /* display black numbered square as error. */
1854 #define DF_FLASH 128 /* background flash is on. */
1855 #define DF_IMPOSSIBLE 256 /* display non-light little square */
1857 struct game_drawstate {
1860 unsigned int *flags; /* width * height */
1865 /* Believe it or not, this empty = "" hack is needed to get around a bug in
1866 * the prc-tools gcc when optimisation is turned on; before, it produced:
1867 lightup-sect.c: In function `interpret_move':
1868 lightup-sect.c:1416: internal error--unrecognizable insn:
1869 (insn 582 580 583 (set (reg:SI 134)
1873 static char *interpret_move(game_state *state, game_ui *ui, const game_drawstate *ds,
1874 int x, int y, int button)
1876 enum { NONE, FLIP_LIGHT, FLIP_IMPOSSIBLE } action = NONE;
1877 int cx = -1, cy = -1;
1879 char buf[80], *nullret = NULL, *empty = "", c;
1881 if (button == LEFT_BUTTON || button == RIGHT_BUTTON) {
1882 if (ui->cur_visible)
1884 ui->cur_visible = 0;
1887 action = (button == LEFT_BUTTON) ? FLIP_LIGHT : FLIP_IMPOSSIBLE;
1888 } else if (IS_CURSOR_SELECT(button) ||
1889 button == 'i' || button == 'I' ||
1890 button == ' ' || button == '\r' || button == '\n') {
1891 if (ui->cur_visible) {
1892 /* Only allow cursor-effect operations if the cursor is visible
1893 * (otherwise you have no idea which square it might be affecting) */
1896 action = (button == 'i' || button == 'I' || button == CURSOR_SELECT2) ?
1897 FLIP_IMPOSSIBLE : FLIP_LIGHT;
1899 ui->cur_visible = 1;
1900 } else if (IS_CURSOR_MOVE(button)) {
1901 move_cursor(button, &ui->cur_x, &ui->cur_y, state->w, state->h, 0);
1902 ui->cur_visible = 1;
1909 case FLIP_IMPOSSIBLE:
1910 if (cx < 0 || cy < 0 || cx >= state->w || cy >= state->h)
1912 flags = GRID(state, flags, cx, cy);
1913 if (flags & F_BLACK)
1915 if (action == FLIP_LIGHT) {
1917 if (flags & F_IMPOSSIBLE || flags & F_LIGHT) c = 'I'; else c = 'L';
1919 if (flags & F_IMPOSSIBLE) return nullret;
1924 if (flags & F_IMPOSSIBLE || flags & F_LIGHT) c = 'L'; else c = 'I';
1926 if (flags & F_LIGHT) return nullret;
1930 sprintf(buf, "%c%d,%d", (int)c, cx, cy);
1937 assert(!"Shouldn't get here!");
1942 static game_state *execute_move(game_state *state, char *move)
1944 game_state *ret = dup_game(state);
1948 if (!*move) goto badmove;
1953 ret->used_solve = TRUE;
1955 } else if (c == 'L' || c == 'I') {
1957 if (sscanf(move, "%d,%d%n", &x, &y, &n) != 2 ||
1958 x < 0 || y < 0 || x >= ret->w || y >= ret->h)
1961 flags = GRID(ret, flags, x, y);
1962 if (flags & F_BLACK) goto badmove;
1964 /* LIGHT and IMPOSSIBLE are mutually exclusive. */
1966 GRID(ret, flags, x, y) &= ~F_IMPOSSIBLE;
1967 set_light(ret, x, y, (flags & F_LIGHT) ? 0 : 1);
1969 set_light(ret, x, y, 0);
1970 GRID(ret, flags, x, y) ^= F_IMPOSSIBLE;
1973 } else goto badmove;
1977 else if (*move) goto badmove;
1979 if (grid_correct(ret)) ret->completed = 1;
1987 /* ----------------------------------------------------------------------
1991 /* XXX entirely cloned from fifteen.c; separate out? */
1992 static void game_compute_size(game_params *params, int tilesize,
1995 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
1996 struct { int tilesize; } ads, *ds = &ads;
1997 ads.tilesize = tilesize;
1999 *x = TILE_SIZE * params->w + 2 * BORDER;
2000 *y = TILE_SIZE * params->h + 2 * BORDER;
2003 static void game_set_size(drawing *dr, game_drawstate *ds,
2004 game_params *params, int tilesize)
2006 ds->tilesize = tilesize;
2007 ds->crad = 3*(tilesize-1)/8;
2010 static float *game_colours(frontend *fe, int *ncolours)
2012 float *ret = snewn(3 * NCOLOURS, float);
2015 frontend_default_colour(fe, &ret[COL_BACKGROUND * 3]);
2017 for (i = 0; i < 3; i++) {
2018 ret[COL_BLACK * 3 + i] = 0.0F;
2019 ret[COL_LIGHT * 3 + i] = 1.0F;
2020 ret[COL_CURSOR * 3 + i] = ret[COL_BACKGROUND * 3 + i] / 2.0F;
2021 ret[COL_GRID * 3 + i] = ret[COL_BACKGROUND * 3 + i] / 1.5F;
2025 ret[COL_ERROR * 3 + 0] = 1.0F;
2026 ret[COL_ERROR * 3 + 1] = 0.25F;
2027 ret[COL_ERROR * 3 + 2] = 0.25F;
2029 ret[COL_LIT * 3 + 0] = 1.0F;
2030 ret[COL_LIT * 3 + 1] = 1.0F;
2031 ret[COL_LIT * 3 + 2] = 0.0F;
2033 *ncolours = NCOLOURS;
2037 static game_drawstate *game_new_drawstate(drawing *dr, game_state *state)
2039 struct game_drawstate *ds = snew(struct game_drawstate);
2042 ds->tilesize = ds->crad = 0;
2043 ds->w = state->w; ds->h = state->h;
2045 ds->flags = snewn(ds->w*ds->h, unsigned int);
2046 for (i = 0; i < ds->w*ds->h; i++)
2054 static void game_free_drawstate(drawing *dr, game_drawstate *ds)
2060 /* At some stage we should put these into a real options struct.
2061 * Note that tile_redraw has no #ifdeffery; it relies on tile_flags not
2062 * to put those flags in. */
2064 #define HINT_OVERLAPS
2065 #define HINT_NUMBERS
2067 static unsigned int tile_flags(game_drawstate *ds, game_state *state, game_ui *ui,
2068 int x, int y, int flashing)
2070 unsigned int flags = GRID(state, flags, x, y);
2071 int lights = GRID(state, lights, x, y);
2072 unsigned int ret = 0;
2074 if (flashing) ret |= DF_FLASH;
2075 if (ui && ui->cur_visible && x == ui->cur_x && y == ui->cur_y)
2078 if (flags & F_BLACK) {
2080 if (flags & F_NUMBERED) {
2082 if (number_wrong(state, x, y))
2083 ret |= DF_NUMBERWRONG;
2089 if (lights > 0) ret |= DF_LIT;
2091 if (flags & F_LIGHT) {
2093 #ifdef HINT_OVERLAPS
2094 if (lights > 1) ret |= DF_OVERLAP;
2097 if (flags & F_IMPOSSIBLE) ret |= DF_IMPOSSIBLE;
2102 static void tile_redraw(drawing *dr, game_drawstate *ds, game_state *state,
2105 unsigned int ds_flags = GRID(ds, flags, x, y);
2106 int dx = COORD(x), dy = COORD(y);
2107 int lit = (ds_flags & DF_FLASH) ? COL_GRID : COL_LIT;
2109 if (ds_flags & DF_BLACK) {
2110 draw_rect(dr, dx, dy, TILE_SIZE, TILE_SIZE, COL_BLACK);
2111 if (ds_flags & DF_NUMBERED) {
2112 int ccol = (ds_flags & DF_NUMBERWRONG) ? COL_ERROR : COL_LIGHT;
2115 /* We know that this won't change over the course of the game
2116 * so it's OK to ignore this when calculating whether or not
2117 * to redraw the tile. */
2118 sprintf(str, "%d", GRID(state, lights, x, y));
2119 draw_text(dr, dx + TILE_SIZE/2, dy + TILE_SIZE/2,
2120 FONT_VARIABLE, TILE_SIZE*3/5,
2121 ALIGN_VCENTRE | ALIGN_HCENTRE, ccol, str);
2124 draw_rect(dr, dx, dy, TILE_SIZE, TILE_SIZE,
2125 (ds_flags & DF_LIT) ? lit : COL_BACKGROUND);
2126 draw_rect_outline(dr, dx, dy, TILE_SIZE, TILE_SIZE, COL_GRID);
2127 if (ds_flags & DF_LIGHT) {
2128 int lcol = (ds_flags & DF_OVERLAP) ? COL_ERROR : COL_LIGHT;
2129 draw_circle(dr, dx + TILE_SIZE/2, dy + TILE_SIZE/2, TILE_RADIUS,
2131 } else if ((ds_flags & DF_IMPOSSIBLE)) {
2132 static int draw_blobs_when_lit = -1;
2133 if (draw_blobs_when_lit < 0) {
2134 char *env = getenv("LIGHTUP_LIT_BLOBS");
2135 draw_blobs_when_lit = (!env || (env[0] == 'y' ||
2138 if (!(ds_flags & DF_LIT) || draw_blobs_when_lit) {
2139 int rlen = TILE_SIZE / 4;
2140 draw_rect(dr, dx + TILE_SIZE/2 - rlen/2,
2141 dy + TILE_SIZE/2 - rlen/2,
2142 rlen, rlen, COL_BLACK);
2147 if (ds_flags & DF_CURSOR) {
2148 int coff = TILE_SIZE/8;
2149 draw_rect_outline(dr, dx + coff, dy + coff,
2150 TILE_SIZE - coff*2, TILE_SIZE - coff*2, COL_CURSOR);
2153 draw_update(dr, dx, dy, TILE_SIZE, TILE_SIZE);
2156 static void game_redraw(drawing *dr, game_drawstate *ds, game_state *oldstate,
2157 game_state *state, int dir, game_ui *ui,
2158 float animtime, float flashtime)
2160 int flashing = FALSE;
2163 if (flashtime) flashing = (int)(flashtime * 3 / FLASH_TIME) != 1;
2167 TILE_SIZE * ds->w + 2 * BORDER,
2168 TILE_SIZE * ds->h + 2 * BORDER, COL_BACKGROUND);
2170 draw_rect_outline(dr, COORD(0)-1, COORD(0)-1,
2171 TILE_SIZE * ds->w + 2,
2172 TILE_SIZE * ds->h + 2,
2175 draw_update(dr, 0, 0,
2176 TILE_SIZE * ds->w + 2 * BORDER,
2177 TILE_SIZE * ds->h + 2 * BORDER);
2181 for (x = 0; x < ds->w; x++) {
2182 for (y = 0; y < ds->h; y++) {
2183 unsigned int ds_flags = tile_flags(ds, state, ui, x, y, flashing);
2184 if (ds_flags != GRID(ds, flags, x, y)) {
2185 GRID(ds, flags, x, y) = ds_flags;
2186 tile_redraw(dr, ds, state, x, y);
2192 static float game_anim_length(game_state *oldstate, game_state *newstate,
2193 int dir, game_ui *ui)
2198 static float game_flash_length(game_state *oldstate, game_state *newstate,
2199 int dir, game_ui *ui)
2201 if (!oldstate->completed && newstate->completed &&
2202 !oldstate->used_solve && !newstate->used_solve)
2207 static int game_status(game_state *state)
2209 return state->completed ? +1 : 0;
2212 static int game_timing_state(game_state *state, game_ui *ui)
2217 static void game_print_size(game_params *params, float *x, float *y)
2222 * I'll use 6mm squares by default.
2224 game_compute_size(params, 600, &pw, &ph);
2229 static void game_print(drawing *dr, game_state *state, int tilesize)
2231 int w = state->w, h = state->h;
2232 int ink = print_mono_colour(dr, 0);
2233 int paper = print_mono_colour(dr, 1);
2236 /* Ick: fake up `ds->tilesize' for macro expansion purposes */
2237 game_drawstate ads, *ds = &ads;
2238 game_set_size(dr, ds, NULL, tilesize);
2243 print_line_width(dr, TILE_SIZE / 16);
2244 draw_rect_outline(dr, COORD(0), COORD(0),
2245 TILE_SIZE * w, TILE_SIZE * h, ink);
2250 print_line_width(dr, TILE_SIZE / 24);
2251 for (x = 1; x < w; x++)
2252 draw_line(dr, COORD(x), COORD(0), COORD(x), COORD(h), ink);
2253 for (y = 1; y < h; y++)
2254 draw_line(dr, COORD(0), COORD(y), COORD(w), COORD(y), ink);
2259 for (y = 0; y < h; y++)
2260 for (x = 0; x < w; x++) {
2261 unsigned int ds_flags = tile_flags(ds, state, NULL, x, y, FALSE);
2262 int dx = COORD(x), dy = COORD(y);
2263 if (ds_flags & DF_BLACK) {
2264 draw_rect(dr, dx, dy, TILE_SIZE, TILE_SIZE, ink);
2265 if (ds_flags & DF_NUMBERED) {
2267 sprintf(str, "%d", GRID(state, lights, x, y));
2268 draw_text(dr, dx + TILE_SIZE/2, dy + TILE_SIZE/2,
2269 FONT_VARIABLE, TILE_SIZE*3/5,
2270 ALIGN_VCENTRE | ALIGN_HCENTRE, paper, str);
2272 } else if (ds_flags & DF_LIGHT) {
2273 draw_circle(dr, dx + TILE_SIZE/2, dy + TILE_SIZE/2,
2274 TILE_RADIUS, -1, ink);
2280 #define thegame lightup
2283 const struct game thegame = {
2284 "Light Up", "games.lightup", "lightup",
2291 TRUE, game_configure, custom_params,
2299 TRUE, game_can_format_as_text_now, game_text_format,
2307 PREFERRED_TILE_SIZE, game_compute_size, game_set_size,
2310 game_free_drawstate,
2315 TRUE, FALSE, game_print_size, game_print,
2316 FALSE, /* wants_statusbar */
2317 FALSE, game_timing_state,
2321 #ifdef STANDALONE_SOLVER
2323 int main(int argc, char **argv)
2327 char *id = NULL, *desc, *err, *result;
2328 int nsol, diff, really_verbose = 0;
2329 unsigned int sflags;
2331 while (--argc > 0) {
2333 if (!strcmp(p, "-v")) {
2335 } else if (*p == '-') {
2336 fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
2344 fprintf(stderr, "usage: %s [-v] <game_id>\n", argv[0]);
2348 desc = strchr(id, ':');
2350 fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
2355 p = default_params();
2356 decode_params(p, id);
2357 err = validate_desc(p, desc);
2359 fprintf(stderr, "%s: %s\n", argv[0], err);
2362 s = new_game(NULL, p, desc);
2364 /* Run the solvers easiest to hardest until we find one that
2365 * can solve our puzzle. If it's soluble we know that the
2366 * hardest (recursive) solver will always find the solution. */
2368 for (diff = 0; diff <= DIFFCOUNT; diff++) {
2369 printf("\nSolving with difficulty %d.\n", diff);
2370 sflags = flags_from_difficulty(diff);
2372 nsol = dosolve(s, sflags, NULL);
2373 if (nsol == 1) break;
2378 printf("Puzzle has no solution.\n");
2379 } else if (nsol < 0) {
2380 printf("Unable to find a unique solution.\n");
2381 } else if (nsol > 1) {
2382 printf("Puzzle has multiple solutions.\n");
2384 verbose = really_verbose;
2386 printf("Puzzle has difficulty %d: solving...\n", diff);
2387 dosolve(s, sflags, NULL); /* sflags from last successful solve */
2388 result = game_text_format(s);
2389 printf("%s", result);
2398 /* vim: set shiftwidth=4 tabstop=8: */