-
Notifications
You must be signed in to change notification settings - Fork 0
/
pearl.c
2686 lines (2329 loc) · 78.5 KB
/
pearl.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
/*
* pearl.c: Nikoli's `Masyu' puzzle.
*/
/*
* TODO:
*
* - The current keyboard cursor mechanism works well on ordinary PC
* keyboards, but for platforms with only arrow keys and a select
* button or two, we may at some point need a simpler one which can
* handle 'x' markings without needing shift keys. For instance, a
* cursor with twice the grid resolution, so that it can range
* across face centres, edge centres and vertices; 'clicks' on face
* centres begin a drag as currently, clicks on edges toggle
* markings, and clicks on vertices are ignored (but it would be
* too confusing not to let the cursor rest on them). But I'm
* pretty sure that would be less pleasant to play on a full
* keyboard, so probably a #ifdef would be the thing.
*
* - Generation is still pretty slow, due to difficulty coming up in
* the first place with a loop that makes a soluble puzzle even
* with all possible clues filled in.
* + A possible alternative strategy to further tuning of the
* existing loop generator would be to throw the entire
* mechanism out and instead write a different generator from
* scratch which evolves the solution along with the puzzle:
* place a few clues, nail down a bit of the loop, place another
* clue, nail down some more, etc. However, I don't have a
* detailed plan for any such mechanism, so it may be a pipe
* dream.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>
#include <math.h>
#include "puzzles.h"
#include "grid.h"
#include "loopgen.h"
#define SWAP(i,j) do { int swaptmp = (i); (i) = (j); (j) = swaptmp; } while (0)
#define NOCLUE 0
#define CORNER 1
#define STRAIGHT 2
#define R 1
#define U 2
#define L 4
#define D 8
#define DX(d) ( ((d)==R) - ((d)==L) )
#define DY(d) ( ((d)==D) - ((d)==U) )
#define F(d) (((d << 2) | (d >> 2)) & 0xF)
#define C(d) (((d << 3) | (d >> 1)) & 0xF)
#define A(d) (((d << 1) | (d >> 3)) & 0xF)
#define LR (L | R)
#define RL (R | L)
#define UD (U | D)
#define DU (D | U)
#define LU (L | U)
#define UL (U | L)
#define LD (L | D)
#define DL (D | L)
#define RU (R | U)
#define UR (U | R)
#define RD (R | D)
#define DR (D | R)
#define BLANK 0
#define UNKNOWN 15
#define bLR (1 << LR)
#define bRL (1 << RL)
#define bUD (1 << UD)
#define bDU (1 << DU)
#define bLU (1 << LU)
#define bUL (1 << UL)
#define bLD (1 << LD)
#define bDL (1 << DL)
#define bRU (1 << RU)
#define bUR (1 << UR)
#define bRD (1 << RD)
#define bDR (1 << DR)
#define bBLANK (1 << BLANK)
enum {
COL_BACKGROUND, COL_HIGHLIGHT, COL_LOWLIGHT,
COL_CURSOR_BACKGROUND = COL_LOWLIGHT,
COL_BLACK, COL_WHITE,
COL_ERROR, COL_GRID, COL_FLASH,
COL_DRAGON, COL_DRAGOFF,
NCOLOURS
};
/* Macro ickery copied from slant.c */
#define DIFFLIST(A) \
A(EASY,Easy,e) \
A(TRICKY,Tricky,t)
#define ENUM(upper,title,lower) DIFF_ ## upper,
#define TITLE(upper,title,lower) #title,
#define ENCODE(upper,title,lower) #lower
#define CONFIG(upper,title,lower) ":" #title
enum { DIFFLIST(ENUM) DIFFCOUNT };
static char const *const pearl_diffnames[] = { DIFFLIST(TITLE) "(count)" };
static char const pearl_diffchars[] = DIFFLIST(ENCODE);
#define DIFFCONFIG DIFFLIST(CONFIG)
struct game_params {
int w, h;
int difficulty;
int nosolve; /* XXX remove me! */
};
struct shared_state {
int w, h, sz;
char *clues; /* size w*h */
int refcnt;
};
#define INGRID(state, gx, gy) ((gx) >= 0 && (gx) < (state)->shared->w && \
(gy) >= 0 && (gy) < (state)->shared->h)
struct game_state {
struct shared_state *shared;
char *lines; /* size w*h: lines placed */
char *errors; /* size w*h: errors detected */
char *marks; /* size w*h: 'no line here' marks placed. */
int completed, used_solve;
int loop_length; /* filled in by check_completion when complete. */
};
#define DEFAULT_PRESET 3
static const struct game_params pearl_presets[] = {
{6, 6, DIFF_EASY},
{6, 6, DIFF_TRICKY},
{8, 8, DIFF_EASY},
{8, 8, DIFF_TRICKY},
{10, 10, DIFF_EASY},
{10, 10, DIFF_TRICKY},
{12, 8, DIFF_EASY},
{12, 8, DIFF_TRICKY},
};
static game_params *default_params(void)
{
game_params *ret = snew(game_params);
*ret = pearl_presets[DEFAULT_PRESET];
ret->nosolve = FALSE;
return ret;
}
static int game_fetch_preset(int i, char **name, game_params **params)
{
game_params *ret;
char buf[64];
if (i < 0 || i >= lenof(pearl_presets)) return FALSE;
ret = default_params();
*ret = pearl_presets[i]; /* struct copy */
*params = ret;
sprintf(buf, "%dx%d %s",
pearl_presets[i].w, pearl_presets[i].h,
pearl_diffnames[pearl_presets[i].difficulty]);
*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;
}
static void decode_params(game_params *ret, char const *string)
{
ret->w = ret->h = atoi(string);
while (*string && isdigit((unsigned char) *string)) ++string;
if (*string == 'x') {
string++;
ret->h = atoi(string);
while (*string && isdigit((unsigned char)*string)) string++;
}
ret->difficulty = DIFF_EASY;
if (*string == 'd') {
int i;
string++;
for (i = 0; i < DIFFCOUNT; i++)
if (*string == pearl_diffchars[i])
ret->difficulty = i;
if (*string) string++;
}
ret->nosolve = FALSE;
if (*string == 'n') {
ret->nosolve = TRUE;
string++;
}
}
static char *encode_params(const game_params *params, int full)
{
char buf[256];
sprintf(buf, "%dx%d", params->w, params->h);
if (full)
sprintf(buf + strlen(buf), "d%c%s",
pearl_diffchars[params->difficulty],
params->nosolve ? "n" : "");
return dupstr(buf);
}
static config_item *game_configure(const game_params *params)
{
config_item *ret;
char buf[64];
ret = snewn(5, config_item);
ret[0].name = "Width";
ret[0].type = C_STRING;
sprintf(buf, "%d", params->w);
ret[0].sval = dupstr(buf);
ret[0].ival = 0;
ret[1].name = "Height";
ret[1].type = C_STRING;
sprintf(buf, "%d", params->h);
ret[1].sval = dupstr(buf);
ret[1].ival = 0;
ret[2].name = "Difficulty";
ret[2].type = C_CHOICES;
ret[2].sval = DIFFCONFIG;
ret[2].ival = params->difficulty;
ret[3].name = "Allow unsoluble";
ret[3].type = C_BOOLEAN;
ret[3].sval = NULL;
ret[3].ival = params->nosolve;
ret[4].name = NULL;
ret[4].type = C_END;
ret[4].sval = NULL;
ret[4].ival = 0;
return ret;
}
static game_params *custom_params(const config_item *cfg)
{
game_params *ret = snew(game_params);
ret->w = atoi(cfg[0].sval);
ret->h = atoi(cfg[1].sval);
ret->difficulty = cfg[2].ival;
ret->nosolve = cfg[3].ival;
return ret;
}
static char *validate_params(const game_params *params, int full)
{
if (params->w < 5) return "Width must be at least five";
if (params->h < 5) return "Height must be at least five";
if (params->difficulty < 0 || params->difficulty >= DIFFCOUNT)
return "Unknown difficulty level";
return NULL;
}
/* ----------------------------------------------------------------------
* Solver.
*/
int pearl_solve(int w, int h, char *clues, char *result,
int difficulty, int partial)
{
int W = 2*w+1, H = 2*h+1;
short *workspace;
int *dsf, *dsfsize;
int x, y, b, d;
int ret = -1;
/*
* workspace[(2*y+1)*W+(2*x+1)] indicates the possible nature
* of the square (x,y), as a logical OR of bitfields.
*
* workspace[(2*y)*W+(2*x+1)], for x odd and y even, indicates
* whether the horizontal edge between (x,y) and (x+1,y) is
* connected (1), disconnected (2) or unknown (3).
*
* workspace[(2*y+1)*W+(2*x)], indicates the same about the
* vertical edge between (x,y) and (x,y+1).
*
* Initially, every square is considered capable of being in
* any of the seven possible states (two straights, four
* corners and empty), except those corresponding to clue
* squares which are more restricted.
*
* Initially, all edges are unknown, except the ones around the
* grid border which are known to be disconnected.
*/
workspace = snewn(W*H, short);
for (x = 0; x < W*H; x++)
workspace[x] = 0;
/* Square states */
for (y = 0; y < h; y++)
for (x = 0; x < w; x++)
switch (clues[y*w+x]) {
case CORNER:
workspace[(2*y+1)*W+(2*x+1)] = bLU|bLD|bRU|bRD;
break;
case STRAIGHT:
workspace[(2*y+1)*W+(2*x+1)] = bLR|bUD;
break;
default:
workspace[(2*y+1)*W+(2*x+1)] = bLR|bUD|bLU|bLD|bRU|bRD|bBLANK;
break;
}
/* Horizontal edges */
for (y = 0; y <= h; y++)
for (x = 0; x < w; x++)
workspace[(2*y)*W+(2*x+1)] = (y==0 || y==h ? 2 : 3);
/* Vertical edges */
for (y = 0; y < h; y++)
for (x = 0; x <= w; x++)
workspace[(2*y+1)*W+(2*x)] = (x==0 || x==w ? 2 : 3);
/*
* We maintain a dsf of connected squares, together with a
* count of the size of each equivalence class.
*/
dsf = snewn(w*h, int);
dsfsize = snewn(w*h, int);
/*
* Now repeatedly try to find something we can do.
*/
while (1) {
int done_something = FALSE;
#ifdef SOLVER_DIAGNOSTICS
for (y = 0; y < H; y++) {
for (x = 0; x < W; x++)
printf("%*x", (x&1) ? 5 : 2, workspace[y*W+x]);
printf("\n");
}
#endif
/*
* Go through the square state words, and discard any
* square state which is inconsistent with known facts
* about the edges around the square.
*/
for (y = 0; y < h; y++)
for (x = 0; x < w; x++) {
for (b = 0; b < 0xD; b++)
if (workspace[(2*y+1)*W+(2*x+1)] & (1<<b)) {
/*
* If any edge of this square is known to
* be connected when state b would require
* it disconnected, or vice versa, discard
* the state.
*/
for (d = 1; d <= 8; d += d) {
int ex = 2*x+1 + DX(d), ey = 2*y+1 + DY(d);
if (workspace[ey*W+ex] ==
((b & d) ? 2 : 1)) {
workspace[(2*y+1)*W+(2*x+1)] &= ~(1<<b);
#ifdef SOLVER_DIAGNOSTICS
printf("edge (%d,%d)-(%d,%d) rules out state"
" %d for square (%d,%d)\n",
ex/2, ey/2, (ex+1)/2, (ey+1)/2,
b, x, y);
#endif
done_something = TRUE;
break;
}
}
}
/*
* Consistency check: each square must have at
* least one state left!
*/
if (!workspace[(2*y+1)*W+(2*x+1)]) {
#ifdef SOLVER_DIAGNOSTICS
printf("edge check at (%d,%d): inconsistency\n", x, y);
#endif
ret = 0;
goto cleanup;
}
}
/*
* Now go through the states array again, and nail down any
* unknown edge if one of its neighbouring squares makes it
* known.
*/
for (y = 0; y < h; y++)
for (x = 0; x < w; x++) {
int edgeor = 0, edgeand = 15;
for (b = 0; b < 0xD; b++)
if (workspace[(2*y+1)*W+(2*x+1)] & (1<<b)) {
edgeor |= b;
edgeand &= b;
}
/*
* Now any bit clear in edgeor marks a disconnected
* edge, and any bit set in edgeand marks a
* connected edge.
*/
/* First check consistency: neither bit is both! */
if (edgeand & ~edgeor) {
#ifdef SOLVER_DIAGNOSTICS
printf("square check at (%d,%d): inconsistency\n", x, y);
#endif
ret = 0;
goto cleanup;
}
for (d = 1; d <= 8; d += d) {
int ex = 2*x+1 + DX(d), ey = 2*y+1 + DY(d);
if (!(edgeor & d) && workspace[ey*W+ex] == 3) {
workspace[ey*W+ex] = 2;
done_something = TRUE;
#ifdef SOLVER_DIAGNOSTICS
printf("possible states of square (%d,%d) force edge"
" (%d,%d)-(%d,%d) to be disconnected\n",
x, y, ex/2, ey/2, (ex+1)/2, (ey+1)/2);
#endif
} else if ((edgeand & d) && workspace[ey*W+ex] == 3) {
workspace[ey*W+ex] = 1;
done_something = TRUE;
#ifdef SOLVER_DIAGNOSTICS
printf("possible states of square (%d,%d) force edge"
" (%d,%d)-(%d,%d) to be connected\n",
x, y, ex/2, ey/2, (ex+1)/2, (ey+1)/2);
#endif
}
}
}
if (done_something)
continue;
/*
* Now for longer-range clue-based deductions (using the
* rules that a corner clue must connect to two straight
* squares, and a straight clue must connect to at least
* one corner square).
*/
for (y = 0; y < h; y++)
for (x = 0; x < w; x++)
switch (clues[y*w+x]) {
case CORNER:
for (d = 1; d <= 8; d += d) {
int ex = 2*x+1 + DX(d), ey = 2*y+1 + DY(d);
int fx = ex + DX(d), fy = ey + DY(d);
int type = d | F(d);
if (workspace[ey*W+ex] == 1) {
/*
* If a corner clue is connected on any
* edge, then we can immediately nail
* down the square beyond that edge as
* being a straight in the appropriate
* direction.
*/
if (workspace[fy*W+fx] != (1<<type)) {
workspace[fy*W+fx] = (1<<type);
done_something = TRUE;
#ifdef SOLVER_DIAGNOSTICS
printf("corner clue at (%d,%d) forces square "
"(%d,%d) into state %d\n", x, y,
fx/2, fy/2, type);
#endif
}
} else if (workspace[ey*W+ex] == 3) {
/*
* Conversely, if a corner clue is
* separated by an unknown edge from a
* square which _cannot_ be a straight
* in the appropriate direction, we can
* mark that edge as disconnected.
*/
if (!(workspace[fy*W+fx] & (1<<type))) {
workspace[ey*W+ex] = 2;
done_something = TRUE;
#ifdef SOLVER_DIAGNOSTICS
printf("corner clue at (%d,%d), plus square "
"(%d,%d) not being state %d, "
"disconnects edge (%d,%d)-(%d,%d)\n",
x, y, fx/2, fy/2, type,
ex/2, ey/2, (ex+1)/2, (ey+1)/2);
#endif
}
}
}
break;
case STRAIGHT:
/*
* If a straight clue is between two squares
* neither of which is capable of being a
* corner connected to it, then the straight
* clue cannot point in that direction.
*/
for (d = 1; d <= 2; d += d) {
int fx = 2*x+1 + 2*DX(d), fy = 2*y+1 + 2*DY(d);
int gx = 2*x+1 - 2*DX(d), gy = 2*y+1 - 2*DY(d);
int type = d | F(d);
if (!(workspace[(2*y+1)*W+(2*x+1)] & (1<<type)))
continue;
if (!(workspace[fy*W+fx] & ((1<<(F(d)|A(d))) |
(1<<(F(d)|C(d))))) &&
!(workspace[gy*W+gx] & ((1<<( d |A(d))) |
(1<<( d |C(d)))))) {
workspace[(2*y+1)*W+(2*x+1)] &= ~(1<<type);
done_something = TRUE;
#ifdef SOLVER_DIAGNOSTICS
printf("straight clue at (%d,%d) cannot corner at "
"(%d,%d) or (%d,%d) so is not state %d\n",
x, y, fx/2, fy/2, gx/2, gy/2, type);
#endif
}
}
/*
* If a straight clue with known direction is
* connected on one side to a known straight,
* then on the other side it must be a corner.
*/
for (d = 1; d <= 8; d += d) {
int fx = 2*x+1 + 2*DX(d), fy = 2*y+1 + 2*DY(d);
int gx = 2*x+1 - 2*DX(d), gy = 2*y+1 - 2*DY(d);
int type = d | F(d);
if (workspace[(2*y+1)*W+(2*x+1)] != (1<<type))
continue;
if (!(workspace[fy*W+fx] &~ (bLR|bUD)) &&
(workspace[gy*W+gx] &~ (bLU|bLD|bRU|bRD))) {
workspace[gy*W+gx] &= (bLU|bLD|bRU|bRD);
done_something = TRUE;
#ifdef SOLVER_DIAGNOSTICS
printf("straight clue at (%d,%d) connecting to "
"straight at (%d,%d) makes (%d,%d) a "
"corner\n", x, y, fx/2, fy/2, gx/2, gy/2);
#endif
}
}
break;
}
if (done_something)
continue;
/*
* Now detect shortcut loops.
*/
{
int nonblanks, loopclass;
dsf_init(dsf, w*h);
for (x = 0; x < w*h; x++)
dsfsize[x] = 1;
/*
* First go through the edge entries and update the dsf
* of which squares are connected to which others. We
* also track the number of squares in each equivalence
* class, and count the overall number of
* known-non-blank squares.
*
* In the process of doing this, we must notice if a
* loop has already been formed. If it has, we blank
* out any square which isn't part of that loop
* (failing a consistency check if any such square does
* not have BLANK as one of its remaining options) and
* exit the deduction loop with success.
*/
nonblanks = 0;
loopclass = -1;
for (y = 1; y < H-1; y++)
for (x = 1; x < W-1; x++)
if ((y ^ x) & 1) {
/*
* (x,y) are the workspace coordinates of
* an edge field. Compute the normal-space
* coordinates of the squares it connects.
*/
int ax = (x-1)/2, ay = (y-1)/2, ac = ay*w+ax;
int bx = x/2, by = y/2, bc = by*w+bx;
/*
* If the edge is connected, do the dsf
* thing.
*/
if (workspace[y*W+x] == 1) {
int ae, be;
ae = dsf_canonify(dsf, ac);
be = dsf_canonify(dsf, bc);
if (ae == be) {
/*
* We have a loop!
*/
if (loopclass != -1) {
/*
* In fact, we have two
* separate loops, which is
* doom.
*/
#ifdef SOLVER_DIAGNOSTICS
printf("two loops found in grid!\n");
#endif
ret = 0;
goto cleanup;
}
loopclass = ae;
} else {
/*
* Merge the two equivalence
* classes.
*/
int size = dsfsize[ae] + dsfsize[be];
dsf_merge(dsf, ac, bc);
ae = dsf_canonify(dsf, ac);
dsfsize[ae] = size;
}
}
} else if ((y & x) & 1) {
/*
* (x,y) are the workspace coordinates of a
* square field. If the square is
* definitely not blank, count it.
*/
if (!(workspace[y*W+x] & bBLANK))
nonblanks++;
}
/*
* If we discovered an existing loop above, we must now
* blank every square not part of it, and exit the main
* deduction loop.
*/
if (loopclass != -1) {
#ifdef SOLVER_DIAGNOSTICS
printf("loop found in grid!\n");
#endif
for (y = 0; y < h; y++)
for (x = 0; x < w; x++)
if (dsf_canonify(dsf, y*w+x) != loopclass) {
if (workspace[(y*2+1)*W+(x*2+1)] & bBLANK) {
workspace[(y*2+1)*W+(x*2+1)] = bBLANK;
} else {
/*
* This square is not part of the
* loop, but is known non-blank. We
* have goofed.
*/
#ifdef SOLVER_DIAGNOSTICS
printf("non-blank square (%d,%d) found outside"
" loop!\n", x, y);
#endif
ret = 0;
goto cleanup;
}
}
/*
* And we're done.
*/
ret = 1;
break;
}
/* Further deductions are considered 'tricky'. */
if (difficulty == DIFF_EASY) goto done_deductions;
/*
* Now go through the workspace again and mark any edge
* which would cause a shortcut loop (i.e. would
* connect together two squares in the same equivalence
* class, and that equivalence class does not contain
* _all_ the known-non-blank squares currently in the
* grid) as disconnected. Also, mark any _square state_
* which would cause a shortcut loop as disconnected.
*/
for (y = 1; y < H-1; y++)
for (x = 1; x < W-1; x++)
if ((y ^ x) & 1) {
/*
* (x,y) are the workspace coordinates of
* an edge field. Compute the normal-space
* coordinates of the squares it connects.
*/
int ax = (x-1)/2, ay = (y-1)/2, ac = ay*w+ax;
int bx = x/2, by = y/2, bc = by*w+bx;
/*
* If the edge is currently unknown, and
* sits between two squares in the same
* equivalence class, and the size of that
* class is less than nonblanks, then
* connecting this edge would be a shortcut
* loop and so we must not do so.
*/
if (workspace[y*W+x] == 3) {
int ae, be;
ae = dsf_canonify(dsf, ac);
be = dsf_canonify(dsf, bc);
if (ae == be) {
/*
* We have a loop. Is it a shortcut?
*/
if (dsfsize[ae] < nonblanks) {
/*
* Yes! Mark this edge disconnected.
*/
workspace[y*W+x] = 2;
done_something = TRUE;
#ifdef SOLVER_DIAGNOSTICS
printf("edge (%d,%d)-(%d,%d) would create"
" a shortcut loop, hence must be"
" disconnected\n", x/2, y/2,
(x+1)/2, (y+1)/2);
#endif
}
}
}
} else if ((y & x) & 1) {
/*
* (x,y) are the workspace coordinates of a
* square field. Go through its possible
* (non-blank) states and see if any gives
* rise to a shortcut loop.
*
* This is slightly fiddly, because we have
* to check whether this square is already
* part of the same equivalence class as
* the things it's joining.
*/
int ae = dsf_canonify(dsf, (y/2)*w+(x/2));
for (b = 2; b < 0xD; b++)
if (workspace[y*W+x] & (1<<b)) {
/*
* Find the equivalence classes of
* the two squares this one would
* connect if it were in this
* state.
*/
int e = -1;
for (d = 1; d <= 8; d += d) if (b & d) {
int xx = x/2 + DX(d), yy = y/2 + DY(d);
int ee = dsf_canonify(dsf, yy*w+xx);
if (e == -1)
ee = e;
else if (e != ee)
e = -2;
}
if (e >= 0) {
/*
* This square state would form
* a loop on equivalence class
* e. Measure the size of that
* loop, and see if it's a
* shortcut.
*/
int loopsize = dsfsize[e];
if (e != ae)
loopsize++;/* add the square itself */
if (loopsize < nonblanks) {
/*
* It is! Mark this square
* state invalid.
*/
workspace[y*W+x] &= ~(1<<b);
done_something = TRUE;
#ifdef SOLVER_DIAGNOSTICS
printf("square (%d,%d) would create a "
"shortcut loop in state %d, "
"hence cannot be\n",
x/2, y/2, b);
#endif
}
}
}
}
}
done_deductions:
if (done_something)
continue;
/*
* If we reach here, there is nothing left we can do.
* Return 2 for ambiguous puzzle.
*/
ret = 2;
break;
}
cleanup:
/*
* If ret = 1 then we've successfully achieved a solution. This
* means that we expect every square to be nailed down to
* exactly one possibility. If this is the case, or if the caller
* asked for a partial solution anyway, transcribe those
* possibilities into the result array.
*/
if (ret == 1 || partial) {
for (y = 0; y < h; y++) {
for (x = 0; x < w; x++) {
for (b = 0; b < 0xD; b++)
if (workspace[(2*y+1)*W+(2*x+1)] == (1<<b)) {
result[y*w+x] = b;
break;
}
if (ret == 1) assert(b < 0xD); /* we should have had a break by now */
}
}
}
sfree(dsfsize);
sfree(dsf);
sfree(workspace);
assert(ret >= 0);
return ret;
}
/* ----------------------------------------------------------------------
* Loop generator.
*/
/*
* We use the loop generator code from loopy, hard-coding to a square
* grid of the appropriate size. Knowing the grid layout and the tile
* size we can shrink that to our small grid and then make our line
* layout from the face colour info.
*
* We provide a bias function to the loop generator which tries to
* bias in favour of loops with more scope for Pearl black clues. This
* seems to improve the success rate of the puzzle generator, in that
* such loops have a better chance of being soluble with all valid
* clues put in.
*/
struct pearl_loopgen_bias_ctx {
/*
* Our bias function counts the number of 'black clue' corners
* (i.e. corners adjacent to two straights) in both the
* BLACK/nonBLACK and WHITE/nonWHITE boundaries. In order to do
* this, we must:
*
* - track the edges that are part of each of those loops
* - track the types of vertex in each loop (corner, straight,
* none)
* - track the current black-clue status of each vertex in each
* loop.
*
* Each of these chunks of data is updated incrementally from the
* previous one, to avoid slowdown due to the bias function
* rescanning the whole grid every time it's called.
*
* So we need a lot of separate arrays, plus a tdq for each one,
* and we must repeat it all twice for the BLACK and WHITE
* boundaries.
*/
struct pearl_loopgen_bias_ctx_boundary {
int colour; /* FACE_WHITE or FACE_BLACK */
char *edges; /* is each edge part of the loop? */
tdq *edges_todo;
char *vertextypes; /* bits 0-3 == outgoing edge bitmap;
* bit 4 set iff corner clue.
* Hence, 0 means non-vertex;
* nonzero but bit 4 zero = straight. */
int *neighbour[2]; /* indices of neighbour vertices in loop */
tdq *vertextypes_todo;
char *blackclues; /* is each vertex a black clue site? */
tdq *blackclues_todo;
} boundaries[2]; /* boundaries[0]=WHITE, [1]=BLACK */
char *faces; /* remember last-seen colour of each face */
tdq *faces_todo;
int score;
grid *g;
};
int pearl_loopgen_bias(void *vctx, char *board, int face)
{
struct pearl_loopgen_bias_ctx *ctx = (struct pearl_loopgen_bias_ctx *)vctx;
grid *g = ctx->g;
int oldface, newface;
int i, j, k;
tdq_add(ctx->faces_todo, face);
while ((j = tdq_remove(ctx->faces_todo)) >= 0) {
oldface = ctx->faces[j];
ctx->faces[j] = newface = board[j];
for (i = 0; i < 2; i++) {
struct pearl_loopgen_bias_ctx_boundary *b = &ctx->boundaries[i];
int c = b->colour;
/*
* If the face has changed either from or to colour c, we need
* to reprocess the edges for this boundary.
*/
if (oldface == c || newface == c) {
grid_face *f = &g->faces[face];
for (k = 0; k < f->order; k++)
tdq_add(b->edges_todo, f->edges[k] - g->edges);
}
}
}
for (i = 0; i < 2; i++) {
struct pearl_loopgen_bias_ctx_boundary *b = &ctx->boundaries[i];
int c = b->colour;
/*
* Go through the to-do list of edges. For each edge, decide
* anew whether it's part of this boundary or not. Any edge
* that changes state has to have both its endpoints put on
* the vertextypes_todo list.
*/
while ((j = tdq_remove(b->edges_todo)) >= 0) {
grid_edge *e = &g->edges[j];
int fc1 = e->face1 ? board[e->face1 - g->faces] : FACE_BLACK;
int fc2 = e->face2 ? board[e->face2 - g->faces] : FACE_BLACK;
int oldedge = b->edges[j];
int newedge = (fc1==c) ^ (fc2==c);
if (oldedge != newedge) {
b->edges[j] = newedge;
tdq_add(b->vertextypes_todo, e->dot1 - g->dots);
tdq_add(b->vertextypes_todo, e->dot2 - g->dots);
}
}
/*
* Go through the to-do list of vertices whose types need
* refreshing. For each one, decide whether it's a corner, a
* straight, or a vertex not in the loop, and in the former
* two cases also work out the indices of its neighbour
* vertices along the loop. Any vertex that changes state must
* be put back on the to-do list for deciding if it's a black
* clue site, and so must its two new neighbours _and_ its two
* old neighbours.
*/
while ((j = tdq_remove(b->vertextypes_todo)) >= 0) {
grid_dot *d = &g->dots[j];
int neighbours[2], type = 0, n = 0;
for (k = 0; k < d->order; k++) {
grid_edge *e = d->edges[k];
grid_dot *d2 = (e->dot1 == d ? e->dot2 : e->dot1);
/* dir == 0,1,2,3 for an edge going L,U,R,D */
int dir = (d->y == d2->y) + 2*(d->x+d->y > d2->x+d2->y);
int ei = e - g->edges;
if (b->edges[ei]) {