-
Notifications
You must be signed in to change notification settings - Fork 1
/
lightup.c
2481 lines (2169 loc) · 76.9 KB
/
lightup.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* lightup.c: Implementation of the Nikoli game 'Light Up'.
*
* Possible future solver enhancements:
*
* - In a situation where two clues are diagonally adjacent, you can
* deduce bounds on the number of lights shared between them. For
* instance, suppose a 3 clue is diagonally adjacent to a 1 clue:
* of the two squares adjacent to both clues, at least one must be
* a light (or the 3 would be unsatisfiable) and yet at most one
* must be a light (or the 1 would be overcommitted), so in fact
* _exactly_ one must be a light, and hence the other two squares
* adjacent to the 3 must also be lights and the other two adjacent
* to the 1 must not. Likewise if the 3 is replaced with a 2 but
* one of its other two squares is known not to be a light, and so
* on.
*
* - In a situation where two clues are orthogonally separated (not
* necessarily directly adjacent), you may be able to deduce
* something about the squares that align with each other. For
* instance, suppose two clues are vertically adjacent. Consider
* the pair of squares A,B horizontally adjacent to the top clue,
* and the pair C,D horizontally adjacent to the bottom clue.
* Assuming no intervening obstacles, A and C align with each other
* and hence at most one of them can be a light, and B and D
* likewise, so we must have at most two lights between the four
* squares. So if the clues indicate that there are at _least_ two
* lights in those four squares because the top clue requires at
* least one of AB to be a light and the bottom one requires at
* least one of CD, then we can in fact deduce that there are
* _exactly_ two lights between the four squares, and fill in the
* other squares adjacent to each clue accordingly. For instance,
* if both clues are 3s, then we instantly deduce that all four of
* the squares _vertically_ adjacent to the two clues must be
* lights. (For that to happen, of course, there'd also have to be
* a black square in between the clues, so the two inner lights
* don't light each other.)
*
* - I haven't thought it through carefully, but there's always the
* possibility that both of the above deductions are special cases
* of some more general pattern which can be made computationally
* feasible...
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>
#include <limits.h>
#ifdef NO_TGMATH_H
# include <math.h>
#else
# include <tgmath.h>
#endif
#include "puzzles.h"
/*
* In standalone solver mode, `verbose' is a variable which can be
* set by command-line option; in debugging mode it's simply always
* true.
*/
#if defined STANDALONE_SOLVER
#define SOLVER_DIAGNOSTICS
static int verbose = 0;
#undef debug
#define debug(x) printf x
#elif defined SOLVER_DIAGNOSTICS
#define verbose 2
#endif
/* --- Constants, structure definitions, etc. --- */
#define PREFERRED_TILE_SIZE 32
#define TILE_SIZE (ds->tilesize)
#define BORDER (TILE_SIZE / 2)
#define TILE_RADIUS (ds->crad)
#define COORD(x) ( (x) * TILE_SIZE + BORDER )
#define FROMCOORD(x) ( ((x) - BORDER + TILE_SIZE) / TILE_SIZE - 1 )
#define FLASH_TIME 0.30F
enum {
COL_BACKGROUND,
COL_GRID,
COL_BLACK, /* black */
COL_LIGHT, /* white */
COL_LIT, /* yellow */
COL_ERROR, /* red */
COL_CURSOR,
NCOLOURS
};
enum { SYMM_NONE, SYMM_REF2, SYMM_ROT2, SYMM_REF4, SYMM_ROT4, SYMM_MAX };
#define DIFFCOUNT 2
struct game_params {
int w, h;
int blackpc; /* %age of black squares */
int symm;
int difficulty; /* 0 to DIFFCOUNT */
};
#define F_BLACK 1
/* flags for black squares */
#define F_NUMBERED 2 /* it has a number attached */
#define F_NUMBERUSED 4 /* this number was useful for solving */
/* flags for non-black squares */
#define F_IMPOSSIBLE 8 /* can't put a light here */
#define F_LIGHT 16
#define F_MARK 32
struct game_state {
int w, h, nlights;
int *lights; /* For black squares, (optionally) the number
of surrounding lights. For non-black squares,
the number of times it's lit. size h*w*/
unsigned int *flags; /* size h*w */
bool completed, used_solve;
};
#define GRID(gs,grid,x,y) (gs->grid[(y)*((gs)->w) + (x)])
/* A ll_data holds information about which lights would be lit by
* a particular grid location's light (or conversely, which locations
* could light a specific other location). */
/* most things should consider this struct opaque. */
typedef struct {
int ox,oy;
int minx, maxx, miny, maxy;
bool include_origin;
} ll_data;
/* Macro that executes 'block' once per light in lld, including
* the origin if include_origin is specified. 'block' can use
* lx and ly as the coords. */
#define FOREACHLIT(lld,block) do { \
int lx,ly; \
ly = (lld)->oy; \
for (lx = (lld)->minx; lx <= (lld)->maxx; lx++) { \
if (lx == (lld)->ox) continue; \
block \
} \
lx = (lld)->ox; \
for (ly = (lld)->miny; ly <= (lld)->maxy; ly++) { \
if (!(lld)->include_origin && ly == (lld)->oy) continue; \
block \
} \
} while(0)
typedef struct {
struct { int x, y; unsigned int f; } points[4];
int npoints;
} surrounds;
/* Fills in (doesn't allocate) a surrounds structure with the grid locations
* around a given square, taking account of the edges. */
static void get_surrounds(const game_state *state, int ox, int oy,
surrounds *s)
{
assert(ox >= 0 && ox < state->w && oy >= 0 && oy < state->h);
s->npoints = 0;
#define ADDPOINT(cond,nx,ny) do {\
if (cond) { \
s->points[s->npoints].x = (nx); \
s->points[s->npoints].y = (ny); \
s->points[s->npoints].f = 0; \
s->npoints++; \
} } while(0)
ADDPOINT(ox > 0, ox-1, oy);
ADDPOINT(ox < (state->w-1), ox+1, oy);
ADDPOINT(oy > 0, ox, oy-1);
ADDPOINT(oy < (state->h-1), ox, oy+1);
}
/* --- Game parameter functions --- */
#define DEFAULT_PRESET 0
static const struct game_params lightup_presets[] = {
{ 7, 7, 20, SYMM_ROT2, 0 },
{ 7, 7, 20, SYMM_ROT2, 1 },
{ 7, 7, 20, SYMM_ROT2, 2 },
{ 10, 10, 20, SYMM_ROT2, 0 },
{ 10, 10, 20, SYMM_ROT2, 1 },
{ 10, 10, 20, SYMM_ROT2, 2 },
#ifdef SLOW_SYSTEM
{ 12, 12, 20, SYMM_ROT2, 0 },
{ 12, 12, 20, SYMM_ROT2, 1 },
{ 12, 12, 20, SYMM_ROT2, 2 },
#else
{ 14, 14, 20, SYMM_ROT2, 0 },
{ 14, 14, 20, SYMM_ROT2, 1 },
{ 14, 14, 20, SYMM_ROT2, 2 }
#endif
};
static game_params *default_params(void)
{
game_params *ret = snew(game_params);
*ret = lightup_presets[DEFAULT_PRESET];
return ret;
}
static bool game_fetch_preset(int i, char **name, game_params **params)
{
game_params *ret;
char buf[80];
if (i < 0 || i >= lenof(lightup_presets))
return false;
ret = default_params();
*ret = lightup_presets[i];
*params = ret;
sprintf(buf, "%dx%d %s",
ret->w, ret->h,
ret->difficulty == 2 ? "hard" :
ret->difficulty == 1 ? "tricky" : "easy");
*name = dupstr(buf);
return true;
}
static void free_params(game_params *params)
{
sfree(params);
}
static game_params *dup_params(const game_params *params)
{
game_params *ret = snew(game_params);
*ret = *params; /* structure copy */
return ret;
}
#define EATNUM(x) do { \
(x) = atoi(string); \
while (*string && isdigit((unsigned char)*string)) string++; \
} while(0)
static void decode_params(game_params *params, char const *string)
{
EATNUM(params->w);
if (*string == 'x') {
string++;
EATNUM(params->h);
}
if (*string == 'b') {
string++;
EATNUM(params->blackpc);
}
if (*string == 's') {
string++;
EATNUM(params->symm);
} else {
/* cope with user input such as '18x10' by ensuring symmetry
* is not selected by default to be incompatible with dimensions */
if (params->symm == SYMM_ROT4 && params->w != params->h)
params->symm = SYMM_ROT2;
}
params->difficulty = 0;
/* cope with old params */
if (*string == 'r') {
params->difficulty = 2;
string++;
}
if (*string == 'd') {
string++;
EATNUM(params->difficulty);
}
}
static char *encode_params(const game_params *params, bool full)
{
char buf[80];
if (full) {
sprintf(buf, "%dx%db%ds%dd%d",
params->w, params->h, params->blackpc,
params->symm,
params->difficulty);
} else {
sprintf(buf, "%dx%d", params->w, params->h);
}
return dupstr(buf);
}
static config_item *game_configure(const game_params *params)
{
config_item *ret;
char buf[80];
ret = snewn(6, config_item);
ret[0].name = "Width";
ret[0].type = C_STRING;
sprintf(buf, "%d", params->w);
ret[0].u.string.sval = dupstr(buf);
ret[1].name = "Height";
ret[1].type = C_STRING;
sprintf(buf, "%d", params->h);
ret[1].u.string.sval = dupstr(buf);
ret[2].name = "%age of black squares";
ret[2].type = C_STRING;
sprintf(buf, "%d", params->blackpc);
ret[2].u.string.sval = dupstr(buf);
ret[3].name = "Symmetry";
ret[3].type = C_CHOICES;
ret[3].u.choices.choicenames = ":None"
":2-way mirror:2-way rotational"
":4-way mirror:4-way rotational";
ret[3].u.choices.selected = params->symm;
ret[4].name = "Difficulty";
ret[4].type = C_CHOICES;
ret[4].u.choices.choicenames = ":Easy:Tricky:Hard";
ret[4].u.choices.selected = params->difficulty;
ret[5].name = NULL;
ret[5].type = C_END;
return ret;
}
static game_params *custom_params(const config_item *cfg)
{
game_params *ret = snew(game_params);
ret->w = atoi(cfg[0].u.string.sval);
ret->h = atoi(cfg[1].u.string.sval);
ret->blackpc = atoi(cfg[2].u.string.sval);
ret->symm = cfg[3].u.choices.selected;
ret->difficulty = cfg[4].u.choices.selected;
return ret;
}
static const char *validate_params(const game_params *params, bool full)
{
if (params->w < 2 || params->h < 2)
return "Width and height must be at least 2";
if (params->w > INT_MAX / params->h)
return "Width times height must not be unreasonably large";
if (full) {
if (params->blackpc < 5 || params->blackpc > 100)
return "Percentage of black squares must be between 5% and 100%";
if (params->w != params->h) {
if (params->symm == SYMM_ROT4)
return "4-fold symmetry is only available with square grids";
}
if ((params->symm == SYMM_ROT4 || params->symm == SYMM_REF4) && params->w < 3 && params->h < 3)
return "Width or height must be at least 3 for 4-way symmetry";
if (params->symm < 0 || params->symm >= SYMM_MAX)
return "Unknown symmetry type";
if (params->difficulty < 0 || params->difficulty > DIFFCOUNT)
return "Unknown difficulty level";
}
return NULL;
}
/* --- Game state construction/freeing helper functions --- */
static game_state *new_state(const game_params *params)
{
game_state *ret = snew(game_state);
ret->w = params->w;
ret->h = params->h;
ret->lights = snewn(ret->w * ret->h, int);
ret->nlights = 0;
memset(ret->lights, 0, ret->w * ret->h * sizeof(int));
ret->flags = snewn(ret->w * ret->h, unsigned int);
memset(ret->flags, 0, ret->w * ret->h * sizeof(unsigned int));
ret->completed = false;
ret->used_solve = false;
return ret;
}
static game_state *dup_game(const game_state *state)
{
game_state *ret = snew(game_state);
ret->w = state->w;
ret->h = state->h;
ret->lights = snewn(ret->w * ret->h, int);
memcpy(ret->lights, state->lights, ret->w * ret->h * sizeof(int));
ret->nlights = state->nlights;
ret->flags = snewn(ret->w * ret->h, unsigned int);
memcpy(ret->flags, state->flags, ret->w * ret->h * sizeof(unsigned int));
ret->completed = state->completed;
ret->used_solve = state->used_solve;
return ret;
}
static void free_game(game_state *state)
{
sfree(state->lights);
sfree(state->flags);
sfree(state);
}
static void debug_state(game_state *state)
{
int x, y;
char c = '?';
(void)c; /* placate -Wunused-but-set-variable if debug() does nothing */
for (y = 0; y < state->h; y++) {
for (x = 0; x < state->w; x++) {
c = '.';
if (GRID(state, flags, x, y) & F_BLACK) {
if (GRID(state, flags, x, y) & F_NUMBERED)
c = GRID(state, lights, x, y) + '0';
else
c = '#';
} else {
if (GRID(state, flags, x, y) & F_LIGHT)
c = 'O';
else if (GRID(state, flags, x, y) & F_IMPOSSIBLE)
c = 'X';
}
debug(("%c", (int)c));
}
debug((" "));
for (x = 0; x < state->w; x++) {
if (GRID(state, flags, x, y) & F_BLACK)
c = '#';
else {
c = (GRID(state, flags, x, y) & F_LIGHT) ? 'A' : 'a';
c += GRID(state, lights, x, y);
}
debug(("%c", (int)c));
}
debug(("\n"));
}
}
/* --- Game completion test routines. --- */
/* These are split up because occasionally functions are only
* interested in one particular aspect. */
/* Returns true if all grid spaces are lit. */
static bool grid_lit(game_state *state)
{
int x, y;
for (x = 0; x < state->w; x++) {
for (y = 0; y < state->h; y++) {
if (GRID(state,flags,x,y) & F_BLACK) continue;
if (GRID(state,lights,x,y) == 0)
return false;
}
}
return true;
}
/* Returns non-zero if any lights are lit by other lights. */
static bool grid_overlap(game_state *state)
{
int x, y;
for (x = 0; x < state->w; x++) {
for (y = 0; y < state->h; y++) {
if (!(GRID(state, flags, x, y) & F_LIGHT)) continue;
if (GRID(state, lights, x, y) > 1)
return true;
}
}
return false;
}
static bool number_wrong(const game_state *state, int x, int y)
{
surrounds s;
int i, n, empty, lights = GRID(state, lights, x, y);
/*
* This function computes the display hint for a number: we
* turn the number red if it is definitely wrong. This means
* that either
*
* (a) it has too many lights around it, or
* (b) it would have too few lights around it even if all the
* plausible squares (not black, lit or F_IMPOSSIBLE) were
* filled with lights.
*/
assert(GRID(state, flags, x, y) & F_NUMBERED);
get_surrounds(state, x, y, &s);
empty = n = 0;
for (i = 0; i < s.npoints; i++) {
if (GRID(state,flags,s.points[i].x,s.points[i].y) & F_LIGHT) {
n++;
continue;
}
if (GRID(state,flags,s.points[i].x,s.points[i].y) & F_BLACK)
continue;
if (GRID(state,flags,s.points[i].x,s.points[i].y) & F_IMPOSSIBLE)
continue;
if (GRID(state,lights,s.points[i].x,s.points[i].y))
continue;
empty++;
}
return (n > lights || (n + empty < lights));
}
static bool number_correct(game_state *state, int x, int y)
{
surrounds s;
int n = 0, i, lights = GRID(state, lights, x, y);
assert(GRID(state, flags, x, y) & F_NUMBERED);
get_surrounds(state, x, y, &s);
for (i = 0; i < s.npoints; i++) {
if (GRID(state,flags,s.points[i].x,s.points[i].y) & F_LIGHT)
n++;
}
return n == lights;
}
/* Returns true if any numbers add up incorrectly. */
static bool grid_addsup(game_state *state)
{
int x, y;
for (x = 0; x < state->w; x++) {
for (y = 0; y < state->h; y++) {
if (!(GRID(state, flags, x, y) & F_NUMBERED)) continue;
if (!number_correct(state, x, y)) return false;
}
}
return true;
}
static bool grid_correct(game_state *state)
{
if (grid_lit(state) &&
!grid_overlap(state) &&
grid_addsup(state)) return true;
return false;
}
/* --- Board initial setup (blacks, lights, numbers) --- */
static void clean_board(game_state *state, bool leave_blacks)
{
int x,y;
for (x = 0; x < state->w; x++) {
for (y = 0; y < state->h; y++) {
if (leave_blacks)
GRID(state, flags, x, y) &= F_BLACK;
else
GRID(state, flags, x, y) = 0;
GRID(state, lights, x, y) = 0;
}
}
state->nlights = 0;
}
static void set_blacks(game_state *state, const game_params *params,
random_state *rs)
{
int x, y, degree = 0, nblack;
bool rotate = false;
int rh, rw, i;
int wodd = (state->w % 2) ? 1 : 0;
int hodd = (state->h % 2) ? 1 : 0;
int xs[4], ys[4];
switch (params->symm) {
case SYMM_NONE: degree = 1; rotate = false; break;
case SYMM_ROT2: degree = 2; rotate = true; break;
case SYMM_REF2: degree = 2; rotate = false; break;
case SYMM_ROT4: degree = 4; rotate = true; break;
case SYMM_REF4: degree = 4; rotate = false; break;
default: assert(!"Unknown symmetry type");
}
if (params->symm == SYMM_ROT4 && (state->h != state->w))
assert(!"4-fold symmetry unavailable without square grid");
if (degree == 4) {
rw = state->w/2;
rh = state->h/2;
if (!rotate) rw += wodd; /* ... but see below. */
rh += hodd;
} else if (degree == 2) {
rw = state->w;
rh = state->h/2;
rh += hodd;
} else {
rw = state->w;
rh = state->h;
}
/* clear, then randomise, required region. */
clean_board(state, false);
nblack = (rw * rh * params->blackpc) / 100;
for (i = 0; i < nblack; i++) {
do {
x = random_upto(rs,rw);
y = random_upto(rs,rh);
} while (GRID(state,flags,x,y) & F_BLACK);
GRID(state, flags, x, y) |= F_BLACK;
}
/* Copy required region. */
if (params->symm == SYMM_NONE) return;
for (x = 0; x < rw; x++) {
for (y = 0; y < rh; y++) {
if (degree == 4) {
xs[0] = x;
ys[0] = y;
xs[1] = state->w - 1 - (rotate ? y : x);
ys[1] = rotate ? x : y;
xs[2] = rotate ? (state->w - 1 - x) : x;
ys[2] = state->h - 1 - y;
xs[3] = rotate ? y : (state->w - 1 - x);
ys[3] = state->h - 1 - (rotate ? x : y);
} else {
xs[0] = x;
ys[0] = y;
xs[1] = rotate ? (state->w - 1 - x) : x;
ys[1] = state->h - 1 - y;
}
for (i = 1; i < degree; i++) {
GRID(state, flags, xs[i], ys[i]) =
GRID(state, flags, xs[0], ys[0]);
}
}
}
/* SYMM_ROT4 misses the middle square above; fix that here. */
if (degree == 4 && rotate && wodd &&
(random_upto(rs,100) <= (unsigned int)params->blackpc))
GRID(state,flags,
state->w/2 + wodd - 1, state->h/2 + hodd - 1) |= F_BLACK;
#ifdef SOLVER_DIAGNOSTICS
if (verbose) debug_state(state);
#endif
}
/* Fills in (does not allocate) a ll_data with all the tiles that would
* be illuminated by a light at point (ox,oy). If origin is true then the
* origin is included in this list. */
static void list_lights(game_state *state, int ox, int oy, bool origin,
ll_data *lld)
{
int x,y;
lld->ox = lld->minx = lld->maxx = ox;
lld->oy = lld->miny = lld->maxy = oy;
lld->include_origin = origin;
y = oy;
for (x = ox-1; x >= 0; x--) {
if (GRID(state, flags, x, y) & F_BLACK) break;
if (x < lld->minx) lld->minx = x;
}
for (x = ox+1; x < state->w; x++) {
if (GRID(state, flags, x, y) & F_BLACK) break;
if (x > lld->maxx) lld->maxx = x;
}
x = ox;
for (y = oy-1; y >= 0; y--) {
if (GRID(state, flags, x, y) & F_BLACK) break;
if (y < lld->miny) lld->miny = y;
}
for (y = oy+1; y < state->h; y++) {
if (GRID(state, flags, x, y) & F_BLACK) break;
if (y > lld->maxy) lld->maxy = y;
}
}
/* Makes sure a light is the given state, editing the lights table to suit the
* new state if necessary. */
static void set_light(game_state *state, int ox, int oy, bool on)
{
ll_data lld;
int diff = 0;
assert(!(GRID(state,flags,ox,oy) & F_BLACK));
if (!on && GRID(state,flags,ox,oy) & F_LIGHT) {
diff = -1;
GRID(state,flags,ox,oy) &= ~F_LIGHT;
state->nlights--;
} else if (on && !(GRID(state,flags,ox,oy) & F_LIGHT)) {
diff = 1;
GRID(state,flags,ox,oy) |= F_LIGHT;
state->nlights++;
}
if (diff != 0) {
list_lights(state,ox,oy,true,&lld);
FOREACHLIT(&lld, GRID(state,lights,lx,ly) += diff; );
}
}
/* Returns 1 if removing a light at (x,y) would cause a square to go dark. */
static int check_dark(game_state *state, int x, int y)
{
ll_data lld;
list_lights(state, x, y, true, &lld);
FOREACHLIT(&lld, if (GRID(state,lights,lx,ly) == 1) { return 1; } );
return 0;
}
/* Sets up an initial random correct position (i.e. every
* space lit, and no lights lit by other lights) by filling the
* grid with lights and then removing lights one by one at random. */
static void place_lights(game_state *state, random_state *rs)
{
int i, x, y, n, *numindices, wh = state->w*state->h;
ll_data lld;
numindices = snewn(wh, int);
for (i = 0; i < wh; i++) numindices[i] = i;
shuffle(numindices, wh, sizeof(*numindices), rs);
/* Place a light on all grid squares without lights. */
for (x = 0; x < state->w; x++) {
for (y = 0; y < state->h; y++) {
GRID(state, flags, x, y) &= ~F_MARK; /* we use this later. */
if (GRID(state, flags, x, y) & F_BLACK) continue;
set_light(state, x, y, true);
}
}
for (i = 0; i < wh; i++) {
y = numindices[i] / state->w;
x = numindices[i] % state->w;
if (!(GRID(state, flags, x, y) & F_LIGHT)) continue;
if (GRID(state, flags, x, y) & F_MARK) continue;
list_lights(state, x, y, false, &lld);
/* If we're not lighting any lights ourself, don't remove anything. */
n = 0;
FOREACHLIT(&lld, if (GRID(state,flags,lx,ly) & F_LIGHT) { n += 1; } );
if (n == 0) continue; /* [1] */
/* Check whether removing lights we're lighting would cause anything
* to go dark. */
n = 0;
FOREACHLIT(&lld, if (GRID(state,flags,lx,ly) & F_LIGHT) { n += check_dark(state,lx,ly); } );
if (n == 0) {
/* No, it wouldn't, so we can remove them all. */
FOREACHLIT(&lld, set_light(state,lx,ly, false); );
GRID(state,flags,x,y) |= F_MARK;
}
if (!grid_overlap(state)) {
sfree(numindices);
return; /* we're done. */
}
assert(grid_lit(state));
}
/* could get here if the line at [1] continue'd out of the loop. */
if (grid_overlap(state)) {
debug_state(state);
assert(!"place_lights failed to resolve overlapping lights!");
}
sfree(numindices);
}
/* Fills in all black squares with numbers of adjacent lights. */
static void place_numbers(game_state *state)
{
int x, y, i, n;
surrounds s;
for (x = 0; x < state->w; x++) {
for (y = 0; y < state->h; y++) {
if (!(GRID(state,flags,x,y) & F_BLACK)) continue;
get_surrounds(state, x, y, &s);
n = 0;
for (i = 0; i < s.npoints; i++) {
if (GRID(state,flags,s.points[i].x, s.points[i].y) & F_LIGHT)
n++;
}
GRID(state,flags,x,y) |= F_NUMBERED;
GRID(state,lights,x,y) = n;
}
}
}
/* --- Actual solver, with helper subroutines. --- */
static void tsl_callback(game_state *state,
int lx, int ly, int *x, int *y, int *n)
{
if (GRID(state,flags,lx,ly) & F_IMPOSSIBLE) return;
if (GRID(state,lights,lx,ly) > 0) return;
*x = lx; *y = ly; (*n)++;
}
static bool try_solve_light(game_state *state, int ox, int oy,
unsigned int flags, int lights)
{
ll_data lld;
int sx = 0, sy = 0, n = 0;
if (lights > 0) return false;
if (flags & F_BLACK) return false;
/* We have an unlit square; count how many ways there are left to
* place a light that lights us (including this square); if only
* one, we must put a light there. Squares that could light us
* are, of course, the same as the squares we would light... */
list_lights(state, ox, oy, true, &lld);
FOREACHLIT(&lld, { tsl_callback(state, lx, ly, &sx, &sy, &n); });
if (n == 1) {
set_light(state, sx, sy, true);
#ifdef SOLVER_DIAGNOSTICS
debug(("(%d,%d) can only be lit from (%d,%d); setting to LIGHT\n",
ox,oy,sx,sy));
if (verbose) debug_state(state);
#endif
return true;
}
return false;
}
static bool could_place_light(unsigned int flags, int lights)
{
if (flags & (F_BLACK | F_IMPOSSIBLE)) return false;
return !(lights > 0);
}
static bool could_place_light_xy(game_state *state, int x, int y)
{
int lights = GRID(state,lights,x,y);
unsigned int flags = GRID(state,flags,x,y);
return could_place_light(flags, lights);
}
/* For a given number square, determine whether we have enough info
* to unambiguously place its lights. */
static bool try_solve_number(game_state *state, int nx, int ny,
unsigned int nflags, int nlights)
{
surrounds s;
int x, y, nl, ns, i, lights;
bool ret = false;
unsigned int flags;
if (!(nflags & F_NUMBERED)) return false;
nl = nlights;
get_surrounds(state,nx,ny,&s);
ns = s.npoints;
/* nl is no. of lights we need to place, ns is no. of spaces we
* have to place them in. Try and narrow these down, and mark
* points we can ignore later. */
for (i = 0; i < s.npoints; i++) {
x = s.points[i].x; y = s.points[i].y;
flags = GRID(state,flags,x,y);
lights = GRID(state,lights,x,y);
if (flags & F_LIGHT) {
/* light here already; one less light for one less place. */
nl--; ns--;
s.points[i].f |= F_MARK;
} else if (!could_place_light(flags, lights)) {
ns--;
s.points[i].f |= F_MARK;
}
}
if (ns == 0) return false; /* nowhere to put anything. */
if (nl == 0) {
/* we have placed all lights we need to around here; all remaining
* surrounds are therefore IMPOSSIBLE. */
GRID(state,flags,nx,ny) |= F_NUMBERUSED;
for (i = 0; i < s.npoints; i++) {
if (!(s.points[i].f & F_MARK)) {
GRID(state,flags,s.points[i].x,s.points[i].y) |= F_IMPOSSIBLE;
ret = true;
}
}
#ifdef SOLVER_DIAGNOSTICS
printf("Clue at (%d,%d) full; setting unlit to IMPOSSIBLE.\n",
nx,ny);
if (verbose) debug_state(state);
#endif
} else if (nl == ns) {
/* we have as many lights to place as spaces; fill them all. */
GRID(state,flags,nx,ny) |= F_NUMBERUSED;
for (i = 0; i < s.npoints; i++) {
if (!(s.points[i].f & F_MARK)) {
set_light(state, s.points[i].x,s.points[i].y, true);
ret = true;
}
}
#ifdef SOLVER_DIAGNOSTICS
printf("Clue at (%d,%d) trivial; setting unlit to LIGHT.\n",
nx,ny);
if (verbose) debug_state(state);
#endif
}
return ret;
}
struct setscratch {
int x, y;
int n;
};
#define SCRATCHSZ (state->w+state->h)
/* New solver algorithm: overlapping sets can add IMPOSSIBLE flags.
* Algorithm thanks to Simon:
*
* (a) Any square where you can place a light has a set of squares
* which would become non-lights as a result. (This includes
* squares lit by the first square, and can also include squares
* adjacent to the same clue square if the new light is the last
* one around that clue.) Call this MAKESDARK(x,y) with (x,y) being
* the square you place a light.
* (b) Any unlit square has a set of squares on which you could place
* a light to illuminate it. (Possibly including itself, of
* course.) This set of squares has the property that _at least
* one_ of them must contain a light. Sets of this type also arise
* from clue squares. Call this MAKESLIGHT(x,y), again with (x,y)
* the square you would place a light.
* (c) If there exists (dx,dy) and (lx,ly) such that MAKESDARK(dx,dy) is
* a superset of MAKESLIGHT(lx,ly), this implies that placing a light at
* (dx,dy) would either leave no remaining way to illuminate a certain
* square, or would leave no remaining way to fulfill a certain clue
* (at lx,ly). In either case, a light can be ruled out at that position.
*
* So, we construct all possible MAKESLIGHT sets, both from unlit squares
* and clue squares, and then we look for plausible MAKESDARK sets that include
* our (lx,ly) to see if we can find a (dx,dy) to rule out. By the time we have
* constructed the MAKESLIGHT set we don't care about (lx,ly), just the set
* members.
*
* Once we have such a set, Simon came up with a Cunning Plan to find
* the most sensible MAKESDARK candidate:
*
* (a) for each square S in your set X, find all the squares which _would_
* rule it out. That means any square which would light S, plus
* any square adjacent to the same clue square as S (provided
* that clue square has only one remaining light to be placed).
* It's not hard to make this list. Don't do anything with this
* data at the moment except _count_ the squares.
* (b) Find the square S_min in the original set which has the
* _smallest_ number of other squares which would rule it out.
* (c) Find all the squares that rule out S_min (it's probably
* better to recompute this than to have stored it during step
* (a), since the CPU requirement is modest but the storage
* cost would get ugly.) For each of these squares, see if it
* rules out everything else in the set X. Any which does can
* be marked as not-a-light.
*
*/
typedef void (*trl_cb)(game_state *state, int dx, int dy,
struct setscratch *scratch, int n, void *ctx);
static void try_rule_out(game_state *state, int x, int y,
struct setscratch *scratch, int n,
trl_cb cb, void *ctx);
static void trl_callback_search(game_state *state, int dx, int dy,
struct setscratch *scratch, int n, void *ignored)
{
int i;
#ifdef SOLVER_DIAGNOSTICS
if (verbose) debug(("discount cb: light at (%d,%d)\n", dx, dy));
#endif
for (i = 0; i < n; i++) {
if (dx == scratch[i].x && dy == scratch[i].y) {