-
Notifications
You must be signed in to change notification settings - Fork 6
/
tracks.c
3064 lines (2619 loc) · 96.4 KB
/
tracks.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
/*
* Implementation of 'Train Tracks', a puzzle from the Times on Saturday.
*
* "Lay tracks to enable the train to travel from village A to village B.
* The numbers indicate how many sections of rail go in each row and
* column. There are only straight rails and curved rails. The track
* cannot cross itself."
*
* Puzzles:
* #9 8x8:d9s5c6zgAa,1,4,1,4,4,3,S3,5,2,2,4,S5,3,3,5,1
* #112 8x8:w6x5mAa,1,3,1,4,6,4,S4,3,3,4,5,2,4,2,S5,1
* #113 8x8:gCx5xAf,1,S4,2,5,4,6,2,3,4,2,5,2,S4,4,5,1
* #114 8x8:p5fAzkAb,1,6,3,3,3,S6,2,3,5,4,S3,3,5,1,5,1
* #115 8x8:zi9d5tAb,1,3,4,5,3,S4,2,4,2,6,2,3,6,S3,3,1
* #942 8x8:n5iCfAzAe,2,2,S5,5,3,5,4,5,4,5,2,S5,3,4,5,3
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>
#include <math.h>
#include "puzzles.h"
/* --- Game parameters --- */
/*
* Difficulty levels. I do some macro ickery here to ensure that my
* enum and the various forms of my name list always match up.
*/
#define DIFFLIST(A) \
A(EASY,Easy,e) \
A(TRICKY,Tricky,t) \
A(HARD,Hard,h) \
/* end of list */
#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 tracks_diffnames[] = { DIFFLIST(TITLE) };
static char const tracks_diffchars[] = DIFFLIST(ENCODE);
#define DIFFCONFIG DIFFLIST(CONFIG)
struct game_params {
int w, h, diff;
bool single_ones;
};
static game_params *default_params(void)
{
game_params *ret = snew(game_params);
ret->w = ret->h = 8;
ret->diff = DIFF_TRICKY;
ret->single_ones = true;
return ret;
}
static const struct game_params tracks_presets[] = {
{8, 8, DIFF_EASY, 1},
{8, 8, DIFF_TRICKY, 1},
{10, 8, DIFF_EASY, 1},
{10, 8, DIFF_TRICKY, 1 },
{10, 10, DIFF_EASY, 1},
{10, 10, DIFF_TRICKY, 1},
{10, 10, DIFF_HARD, 1},
{15, 10, DIFF_EASY, 1},
{15, 10, DIFF_TRICKY, 1},
{15, 15, DIFF_EASY, 1},
{15, 15, DIFF_TRICKY, 1},
{15, 15, DIFF_HARD, 1},
};
static bool game_fetch_preset(int i, char **name, game_params **params)
{
game_params *ret;
char str[80];
if (i < 0 || i >= lenof(tracks_presets))
return false;
ret = snew(game_params);
*ret = tracks_presets[i];
sprintf(str, "%dx%d %s", ret->w, ret->h, tracks_diffnames[ret->diff]);
*name = dupstr(str);
*params = ret;
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 *params, char const *string)
{
params->w = params->h = atoi(string);
while (*string && isdigit((unsigned char)*string)) string++;
if (*string == 'x') {
string++;
params->h = atoi(string);
while (*string && isdigit((unsigned char)*string)) string++;
}
if (*string == 'd') {
int i;
string++;
params->diff = DIFF_TRICKY;
for (i = 0; i < DIFFCOUNT; i++)
if (*string == tracks_diffchars[i])
params->diff = i;
if (*string) string++;
}
params->single_ones = true;
if (*string == 'o') {
params->single_ones = false;
string++;
}
}
static char *encode_params(const game_params *params, bool full)
{
char buf[120];
sprintf(buf, "%dx%d", params->w, params->h);
if (full)
sprintf(buf + strlen(buf), "d%c%s",
tracks_diffchars[params->diff],
params->single_ones ? "" : "o");
return dupstr(buf);
}
static config_item *game_configure(const game_params *params)
{
config_item *ret;
char buf[80];
ret = snewn(5, 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 = "Difficulty";
ret[2].type = C_CHOICES;
ret[2].u.choices.choicenames = DIFFCONFIG;
ret[2].u.choices.selected = params->diff;
ret[3].name = "Disallow consecutive 1 clues";
ret[3].type = C_BOOLEAN;
ret[3].u.boolean.bval = params->single_ones;
ret[4].name = NULL;
ret[4].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->diff = cfg[2].u.choices.selected;
ret->single_ones = cfg[3].u.boolean.bval;
return ret;
}
static const char *validate_params(const game_params *params, bool full)
{
/*
* Generating anything under 4x4 runs into trouble of one kind
* or another.
*/
if (params->w < 4 || params->h < 4)
return "Width and height must both be at least four";
return NULL;
}
/* --- Game state --- */
/* flag usage copied from pearl */
#define R 1
#define U 2
#define L 4
#define D 8
#define MOVECHAR(m) ((m==R)?'R':(m==U)?'U':(m==L)?'L':(m==D)?'D':'?')
#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 ALLDIR 15
#define BLANK 0
#define UNKNOWN 15
static const int nbits[] = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 };
/* square grid flags */
#define S_TRACK 1 /* a track passes through this square (--> 2 edges) */
#define S_NOTRACK 2 /* no track passes through this square */
#define S_ERROR 4
#define S_CLUE 8
#define S_MARK 16
#define S_TRACK_SHIFT 16 /* U/D/L/R flags for edge track indicators */
#define S_NOTRACK_SHIFT 20 /* U/D/L/R flags for edge no-track indicators */
/* edge grid flags */
#define E_TRACK 1 /* a track passes through this edge */
#define E_NOTRACK 2 /* no track passes through this edge */
struct numbers {
int refcount;
int *numbers; /* sz w+h */
int row_s, col_s; /* stations: TODO think about multiple lines
(for bigger grids)? */
};
#define INGRID(state, gx, gy) ((gx) >= 0 && (gx) < (state)->p.w && \
(gy) >= 0 && (gy) < (state)->p.h)
struct game_state {
game_params p;
unsigned int *sflags; /* size w*h */
struct numbers *numbers;
int *num_errors; /* size w+h */
bool completed, used_solve, impossible;
};
/* Return the four directions in which a particular edge flag is set, around a square. */
static int S_E_DIRS(const game_state *state, int sx, int sy,
unsigned int eflag) {
return (state->sflags[sy*state->p.w+sx] >>
((eflag == E_TRACK) ? S_TRACK_SHIFT : S_NOTRACK_SHIFT)) & ALLDIR;
}
/* Count the number of a particular edge flag around a grid square. */
static int S_E_COUNT(const game_state *state, int sx, int sy,
unsigned int eflag) {
return nbits[S_E_DIRS(state, sx, sy, eflag)];
}
/* Return the two flags (E_TRACK and/or E_NOTRACK) set on a specific
* edge of a square. */
static unsigned S_E_FLAGS(const game_state *state, int sx, int sy, int d) {
unsigned f = state->sflags[sy*state->p.w+sx];
int t = (f & (d << S_TRACK_SHIFT)), nt = (f & (d << S_NOTRACK_SHIFT));
return (t ? E_TRACK : 0) | (nt ? E_NOTRACK : 0);
}
static bool S_E_ADJ(const game_state *state, int sx, int sy, int d, int *ax,
int *ay, unsigned int *ad) {
if (d == L && sx > 0) { *ax = sx-1; *ay = sy; *ad = R; return true; }
if (d == R && sx < state->p.w-1) { *ax = sx+1; *ay = sy; *ad = L; return true; }
if (d == U && sy > 0) { *ax = sx; *ay = sy-1; *ad = D; return true; }
if (d == D && sy < state->p.h-1) { *ax = sx; *ay = sy+1; *ad = U; return true; }
return false;
}
/* Sets flag (E_TRACK or E_NOTRACK) on a given edge of a square. */
static void S_E_SET(game_state *state, int sx, int sy, int d,
unsigned int eflag) {
unsigned shift = (eflag == E_TRACK) ? S_TRACK_SHIFT : S_NOTRACK_SHIFT, ad;
int ax, ay;
state->sflags[sy*state->p.w+sx] |= (d << shift);
if (S_E_ADJ(state, sx, sy, d, &ax, &ay, &ad)) {
state->sflags[ay*state->p.w+ax] |= (ad << shift);
}
}
/* Clears flag (E_TRACK or E_NOTRACK) on a given edge of a square. */
static void S_E_CLEAR(game_state *state, int sx, int sy, int d,
unsigned int eflag) {
unsigned shift = (eflag == E_TRACK) ? S_TRACK_SHIFT : S_NOTRACK_SHIFT, ad;
int ax, ay;
state->sflags[sy*state->p.w+sx] &= ~(d << shift);
if (S_E_ADJ(state, sx, sy, d, &ax, &ay, &ad)) {
state->sflags[ay*state->p.w+ax] &= ~(ad << shift);
}
}
static void clear_game(game_state *state)
{
int w = state->p.w, h = state->p.h;
memset(state->sflags, 0, w*h * sizeof(unsigned int));
memset(state->numbers->numbers, 0, (w+h) * sizeof(int));
state->numbers->col_s = state->numbers->row_s = -1;
memset(state->num_errors, 0, (w+h) * sizeof(int));
state->completed = state->used_solve = state->impossible = false;
}
static game_state *blank_game(const game_params *params)
{
game_state *state = snew(game_state);
int w = params->w, h = params->h;
state->p = *params;
state->sflags = snewn(w*h, unsigned int);
state->numbers = snew(struct numbers);
state->numbers->refcount = 1;
state->numbers->numbers = snewn(w+h, int);
state->num_errors = snewn(w+h, int);
clear_game(state);
return state;
}
static void copy_game_flags(const game_state *src, game_state *dest)
{
int w = src->p.w, h = src->p.h;
memcpy(dest->sflags, src->sflags, w*h*sizeof(unsigned int));
}
static game_state *dup_game(const game_state *state)
{
int w = state->p.w, h = state->p.h;
game_state *ret = snew(game_state);
ret->p = state->p; /* structure copy */
ret->sflags = snewn(w*h, unsigned int);
copy_game_flags(state, ret);
ret->numbers = state->numbers;
state->numbers->refcount++;
ret->num_errors = snewn(w+h, int);
memcpy(ret->num_errors, state->num_errors, (w+h)*sizeof(int));
ret->completed = state->completed;
ret->used_solve = state->used_solve;
ret->impossible = state->impossible;
return ret;
}
static void free_game(game_state *state)
{
if (--state->numbers->refcount <= 0) {
sfree(state->numbers->numbers);
sfree(state->numbers);
}
sfree(state->num_errors);
sfree(state->sflags);
sfree(state);
}
#define NDIRS 4
static const unsigned int dirs_const[] = { U, D, L, R };
static unsigned int find_direction(game_state *state, random_state *rs,
int x, int y)
{
int i, nx, ny, w=state->p.w, h=state->p.h;
unsigned int dirs[NDIRS];
memcpy(dirs, dirs_const, sizeof(dirs));
shuffle(dirs, NDIRS, sizeof(*dirs), rs);
for (i = 0; i < NDIRS; i++) {
nx = x + DX(dirs[i]);
ny = y + DY(dirs[i]);
if (nx >= 0 && nx < w && ny == h) {
/* off the bottom of the board: we've finished the path. */
return dirs[i];
} else if (!INGRID(state, nx, ny)) {
/* off the board: can't move here */
continue;
} else if (S_E_COUNT(state, nx, ny, E_TRACK) > 0) {
/* already tracks here: can't move */
continue;
}
return dirs[i];
}
return 0; /* no possible directions left. */
}
static bool check_completion(game_state *state, bool mark);
static void lay_path(game_state *state, random_state *rs)
{
int px, py, w=state->p.w, h=state->p.h;
unsigned int d;
start:
clear_game(state);
/* pick a random entry point, lay its left edge */
state->numbers->row_s = py = random_upto(rs, h);
px = 0;
S_E_SET(state, px, py, L, E_TRACK);
while (INGRID(state, px, py)) {
d = find_direction(state, rs, px, py);
if (d == 0)
goto start; /* nowhere else to go, restart */
S_E_SET(state, px, py, d, E_TRACK);
px += DX(d);
py += DY(d);
}
/* double-check we got to the right place */
assert(px >= 0 && px < w && py == h);
state->numbers->col_s = px;
}
static int tracks_solve(game_state *state, int diff, int *max_diff_out);
static void debug_state(game_state *state, const char *what);
/* Clue-setting algorithm:
- first lay clues randomly until it's soluble
- then remove clues randomly if removing them doesn't affect solubility
- We start with two clues, one at each path entrance.
More details:
- start with an array of all square i positions
- if the grid is already soluble by a level easier than we've requested,
go back and make a new grid
- if the grid is already soluble by our requested difficulty level, skip
the clue-laying step
- count the number of flags the solver managed to place, remember this.
- to lay clues:
- shuffle the i positions
- for each possible clue position:
- copy the solved board, strip it
- take the next position, add a clue there on the copy
- try and solve the copy
- if it's soluble by a level easier than we've requested, continue (on
to next clue position: putting a clue here makes it too easy)
- if it's soluble by our difficulty level, we're done:
- put the clue flag into the solved board
- go to strip-clues.
- if the solver didn't manage to place any more flags, continue (on to next
clue position: putting a clue here didn't help he solver)
- otherwise put the clue flag in the original board, and go on to the next
clue position
- if we get here and we've not solved it yet, we never will (did we really
fill _all_ the clues in?!). Go back and make a new grid.
- to strip clues:
- shuffle the i positions
- for each possible clue position:
- if the solved grid doesn't have a clue here, skip
- copy the solved board, remove this clue, strip it
- try and solve the copy
- assert that it is not soluble by a level easier than we've requested
- (because this should never happen)
- if this is (still) soluble by our difficulty level:
- remove this clue from the solved board, it's redundant (with the other
clues)
- that should be it.
*/
static game_state *copy_and_strip(const game_state *state, game_state *ret, int flipcluei)
{
int i, j, w = state->p.w, h = state->p.h;
copy_game_flags(state, ret);
/* Add/remove a clue before stripping, if required */
if (flipcluei != -1)
ret->sflags[flipcluei] ^= S_CLUE;
/* All squares that are not clue squares have square track info erased, and some edge flags.. */
for (i = 0; i < w*h; i++) {
if (!(ret->sflags[i] & S_CLUE)) {
ret->sflags[i] &= ~(S_TRACK|S_NOTRACK|S_ERROR|S_MARK);
for (j = 0; j < 4; j++) {
unsigned f = 1<<j;
int xx = i%w + DX(f), yy = i/w + DY(f);
if (!INGRID(state, xx, yy) || !(ret->sflags[yy*w+xx] & S_CLUE)) {
/* only erase an edge flag if neither side of the edge is S_CLUE. */
S_E_CLEAR(ret, i%w, i/w, f, E_TRACK);
S_E_CLEAR(ret, i%w, i/w, f, E_NOTRACK);
}
}
}
}
return ret;
}
#ifdef STANDALONE_SOLVER
#include <stdarg.h>
static FILE *solver_diagnostics_fp = NULL;
static void solver_diagnostic(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vfprintf(solver_diagnostics_fp, fmt, ap);
va_end(ap);
fputc('\n', solver_diagnostics_fp);
}
#define solverdebug(printf_params) do { \
if (solver_diagnostics_fp) { \
solver_diagnostic printf_params; \
} \
} while (0)
#else
#define solverdebug(printf_params) ((void)0)
#endif
static int solve_progress(const game_state *state) {
int i, w = state->p.w, h = state->p.h, progress = 0;
/* Work out how many flags the solver managed to set (either TRACK
or NOTRACK) and return this as a progress measure, to check whether
a partially-solved board gets any further than a previous partially-
solved board. */
for (i = 0; i < w*h; i++) {
if (state->sflags[i] & S_TRACK) progress++;
if (state->sflags[i] & S_NOTRACK) progress++;
progress += S_E_COUNT(state, i%w, i/w, E_TRACK);
progress += S_E_COUNT(state, i%w, i/w, E_NOTRACK);
}
return progress;
}
static bool check_phantom_moves(const game_state *state) {
int x, y, i;
/* Check that this state won't show 'phantom moves' at the start of the
* game: squares which have multiple edge flags set but no clue flag
* cause a piece of track to appear that isn't on a clue square. */
for (x = 0; x < state->p.w; x++) {
for (y = 0; y < state->p.h; y++) {
i = y*state->p.w+x;
if (state->sflags[i] & S_CLUE)
continue;
if (S_E_COUNT(state, x, y, E_TRACK) > 1)
return true; /* found one! */
}
}
return false;
}
static int add_clues(game_state *state, random_state *rs, int diff)
{
int i, j, pi, w = state->p.w, h = state->p.h, progress, ret = 0, sr;
int *positions = snewn(w*h, int), npositions = 0;
int *nedges_previous_solve = snewn(w*h, int);
game_state *scratch = dup_game(state);
int diff_used;
debug_state(state, "gen: Initial board");
debug(("gen: Adding clues..."));
/* set up the shuffly-position grid for later, used for adding clues:
* we only bother adding clues where any edges are set. */
for (i = 0; i < w*h; i++) {
if (S_E_DIRS(state, i%w, i/w, E_TRACK) != 0) {
positions[npositions++] = i;
}
nedges_previous_solve[i] = 0;
}
/* First, check whether the puzzle is already either too easy, or just right */
scratch = copy_and_strip(state, scratch, -1);
sr = tracks_solve(scratch, diff, &diff_used);
if (diff_used < diff) {
ret = -1; /* already too easy, even without adding clues. */
debug(("gen: ...already too easy, need new board."));
goto done;
}
if (sr < 0)
assert(!"Generator should not have created impossible puzzle");
if (sr > 0) {
ret = 1; /* already soluble without any extra clues. */
debug(("gen: ...soluble without clues, nothing to do."));
goto done;
}
debug_state(scratch, "gen: Initial part-solved state: ");
progress = solve_progress(scratch);
debug(("gen: Initial solve progress is %d", progress));
/* First, lay clues until we're soluble. */
shuffle(positions, npositions, sizeof(int), rs);
for (pi = 0; pi < npositions; pi++) {
i = positions[pi]; /* pick a random position */
if (state->sflags[i] & S_CLUE)
continue; /* already a clue here (entrance location?) */
if (nedges_previous_solve[i] == 2)
continue; /* no point putting a clue here, we could solve both edges
with the previous set of clues */
/* set a clue in that position (on a copy of the board) and test solubility */
scratch = copy_and_strip(state, scratch, i);
if (check_phantom_moves(scratch))
continue; /* adding a clue here would add phantom track */
if (tracks_solve(scratch, diff, &diff_used) > 0) {
if (diff_used < diff) {
continue; /* adding a clue here makes it too easy */
}
/* we're now soluble (and we weren't before): add this clue, and then
start stripping clues */
debug(("gen: ...adding clue at (%d,%d), now soluble", i%w, i/w));
state->sflags[i] |= S_CLUE;
goto strip_clues;
}
if (solve_progress(scratch) > progress) {
/* We've made more progress solving: add this clue, then. */
progress = solve_progress(scratch);
debug(("gen: ... adding clue at (%d,%d), new progress %d", i%w, i/w, progress));
state->sflags[i] |= S_CLUE;
for (j = 0; j < w*h; j++)
nedges_previous_solve[j] = S_E_COUNT(scratch, j%w, j/w, E_TRACK);
}
}
/* If we got here we didn't ever manage to make the puzzle soluble
(without making it too easily soluble, that is): give up. */
debug(("gen: Unable to make soluble with clues, need new board."));
ret = -1;
goto done;
strip_clues:
debug(("gen: Stripping clues."));
/* Now, strip redundant clues (i.e. those without which the puzzle is still
soluble) */
shuffle(positions, npositions, sizeof(int), rs);
for (pi = 0; pi < npositions; pi++) {
i = positions[pi]; /* pick a random position */
if (!(state->sflags[i] & S_CLUE))
continue; /* no clue here to strip */
if ((i%w == 0 && i/w == state->numbers->row_s) ||
(i/w == (h-1) && i%w == state->numbers->col_s))
continue; /* don't strip clues at entrance/exit */
scratch = copy_and_strip(state, scratch, i);
if (check_phantom_moves(scratch))
continue; /* removing a clue here would add phantom track */
if (tracks_solve(scratch, diff, NULL) > 0) {
debug(("gen: ... removing clue at (%d,%d), still soluble without it", i%w, i/w));
state->sflags[i] &= ~S_CLUE; /* still soluble without this clue. */
}
}
debug(("gen: Finished stripping clues."));
ret = 1;
done:
sfree(positions);
sfree(nedges_previous_solve);
free_game(scratch);
return ret;
}
static char *new_game_desc(const game_params *params, random_state *rs,
char **aux, bool interactive)
{
int i, j, w = params->w, h = params->h, x, y, ret;
game_state *state;
char *desc, *p;
game_params adjusted_params;
/*
* 4x4 Tricky cannot be generated, so fall back to Easy.
*/
if (w == 4 && h == 4 && params->diff > DIFF_EASY) {
adjusted_params = *params; /* structure copy */
adjusted_params.diff = DIFF_EASY;
params = &adjusted_params;
}
state = blank_game(params);
/* --- lay the random path */
newpath:
lay_path(state, rs);
for (x = 0; x < w; x++) {
for (y = 0; y < h; y++) {
if (S_E_COUNT(state, x, y, E_TRACK) > 0) {
state->sflags[y*w + x] |= S_TRACK;
}
if ((x == 0 && y == state->numbers->row_s) ||
(y == (h-1) && x == state->numbers->col_s)) {
state->sflags[y*w + x] |= S_CLUE;
}
}
}
/* --- Update the clue numbers based on the tracks we have generated. */
for (x = 0; x < w; x++) {
for (y = 0; y < h; y++) {
if (state->sflags[y*w + x] & S_TRACK) {
state->numbers->numbers[x]++;
state->numbers->numbers[y+w]++;
}
}
}
for (i = 0; i < w+h; i++) {
if (state->numbers->numbers[i] == 0)
goto newpath; /* too boring */
}
if (params->single_ones) {
bool last_was_one = true, is_one; /* disallow 1 clue at entry point */
for (i = 0; i < w+h; i++) {
is_one = (state->numbers->numbers[i] == 1);
if (is_one && last_was_one)
goto newpath; /* disallow consecutive 1 clues. */
last_was_one = is_one;
}
if (state->numbers->numbers[w+h-1] == 1)
goto newpath; /* (disallow 1 clue at exit point) */
}
/* --- Add clues to make a soluble puzzle */
ret = add_clues(state, rs, params->diff);
if (ret != 1) goto newpath; /* couldn't make it soluble, or too easy */
/* --- Generate the game desc based on the generated grid. */
desc = snewn(w*h*3 + (w+h)*5, char);
for (i = j = 0; i < w*h; i++) {
if (!(state->sflags[i] & S_CLUE) && j > 0 &&
desc[j-1] >= 'a' && desc[j-1] < 'z')
desc[j-1]++;
else if (!(state->sflags[i] & S_CLUE))
desc[j++] = 'a';
else {
unsigned int f = S_E_DIRS(state, i%w, i/w, E_TRACK);
desc[j++] = (f < 10) ? ('0' + f) : ('A' + (f-10));
}
}
p = desc + j;
for (x = 0; x < w; x++) {
p += sprintf(p, ",%s%d", x == state->numbers->col_s ? "S" : "",
state->numbers->numbers[x]);
}
for (y = 0; y < h; y++) {
p += sprintf(p, ",%s%d", y == state->numbers->row_s ? "S" : "",
state->numbers->numbers[y+w]);
}
*p++ = '\0';
ret = tracks_solve(state, DIFFCOUNT, NULL);
assert(ret >= 0);
free_game(state);
debug(("new_game_desc: %s", desc));
return desc;
}
static const char *validate_desc(const game_params *params, const char *desc)
{
int i = 0, w = params->w, h = params->h, in = 0, out = 0;
while (*desc) {
unsigned int f = 0;
if (*desc >= '0' && *desc <= '9')
f = (*desc - '0');
else if (*desc >= 'A' && *desc <= 'F')
f = (*desc - 'A' + 10);
else if (*desc >= 'a' && *desc <= 'z')
i += *desc - 'a';
else
return "Game description contained unexpected characters";
if (f != 0) {
if (nbits[f] != 2)
return "Clue did not provide 2 direction flags";
}
i++;
desc++;
if (i == w*h) break;
}
for (i = 0; i < w+h; i++) {
if (!*desc)
return "Not enough numbers given after grid specification";
else if (*desc != ',')
return "Invalid character in number list";
desc++;
if (*desc == 'S') {
if (i < w)
out++;
else
in++;
desc++;
}
while (*desc && isdigit((unsigned char)*desc)) desc++;
}
if (in != 1 || out != 1)
return "Puzzle must have one entrance and one exit";
if (*desc)
return "Unexpected additional character at end of game description";
return NULL;
}
static game_state *new_game(midend *me, const game_params *params, const char *desc)
{
game_state *state = blank_game(params);
int w = params->w, h = params->h, i = 0;
while (*desc) {
unsigned int f = 0;
if (*desc >= '0' && *desc <= '9')
f = (*desc - '0');
else if (*desc >= 'A' && *desc <= 'F')
f = (*desc - 'A' + 10);
else if (*desc >= 'a' && *desc <= 'z')
i += *desc - 'a';
if (f != 0) {
int x = i % w, y = i / w;
assert(f < 16);
assert(nbits[f] == 2);
state->sflags[i] |= (S_TRACK | S_CLUE);
if (f & U) S_E_SET(state, x, y, U, E_TRACK);
if (f & D) S_E_SET(state, x, y, D, E_TRACK);
if (f & L) S_E_SET(state, x, y, L, E_TRACK);
if (f & R) S_E_SET(state, x, y, R, E_TRACK);
}
i++;
desc++;
if (i == w*h) break;
}
for (i = 0; i < w+h; i++) {
assert(*desc == ',');
desc++;
if (*desc == 'S') {
if (i < w)
state->numbers->col_s = i;
else
state->numbers->row_s = i-w;
desc++;
}
state->numbers->numbers[i] = atoi(desc);
while (*desc && isdigit((unsigned char)*desc)) desc++;
}
assert(!*desc);
return state;
}
struct solver_scratch {
int *dsf;
};
static int solve_set_sflag(game_state *state, int x, int y,
unsigned int f, const char *why)
{
int w = state->p.w, i = y*w + x;
if (state->sflags[i] & f)
return 0;
solverdebug(("square (%d,%d) -> %s: %s",
x, y, (f == S_TRACK ? "TRACK" : "NOTRACK"), why));
if (state->sflags[i] & (f == S_TRACK ? S_NOTRACK : S_TRACK)) {
solverdebug(("opposite flag already set there, marking IMPOSSIBLE"));
state->impossible = true;
}
state->sflags[i] |= f;
return 1;
}
static int solve_set_eflag(game_state *state, int x, int y, int d,
unsigned int f, const char *why)
{
int sf = S_E_FLAGS(state, x, y, d);
if (sf & f)
return 0;
solverdebug(("edge (%d,%d)/%c -> %s: %s", x, y,
(d == U) ? 'U' : (d == D) ? 'D' : (d == L) ? 'L' : 'R',
(f == S_TRACK ? "TRACK" : "NOTRACK"), why));
if (sf & (f == E_TRACK ? E_NOTRACK : E_TRACK)) {
solverdebug(("opposite flag already set there, marking IMPOSSIBLE"));
state->impossible = true;
}
S_E_SET(state, x, y, d, f);
return 1;
}
static int solve_update_flags(game_state *state)
{
int x, y, i, w = state->p.w, h = state->p.h, did = 0;
for (x = 0; x < w; x++) {
for (y = 0; y < h; y++) {
/* If a square is NOTRACK, all four edges must be. */
if (state->sflags[y*w + x] & S_NOTRACK) {
for (i = 0; i < 4; i++) {
unsigned int d = 1<<i;
did += solve_set_eflag(state, x, y, d, E_NOTRACK, "edges around NOTRACK");
}
}
/* If 3 or more edges around a square are NOTRACK, the square is. */
if (S_E_COUNT(state, x, y, E_NOTRACK) >= 3) {
did += solve_set_sflag(state, x, y, S_NOTRACK, "square has >2 NOTRACK edges");
}
/* If any edge around a square is TRACK, the square is. */
if (S_E_COUNT(state, x, y, E_TRACK) > 0) {
did += solve_set_sflag(state, x, y, S_TRACK, "square has TRACK edge");
}
/* If a square is TRACK and 2 edges are NOTRACK,
the other two edges must be TRACK. */
if ((state->sflags[y*w + x] & S_TRACK) &&
(S_E_COUNT(state, x, y, E_NOTRACK) == 2) &&
(S_E_COUNT(state, x, y, E_TRACK) < 2)) {
for (i = 0; i < 4; i++) {
unsigned int d = 1<<i;
if (!(S_E_FLAGS(state, x, y, d) & (E_TRACK|E_NOTRACK))) {
did += solve_set_eflag(state, x, y, d, E_TRACK,
"TRACK square/2 NOTRACK edges");
}
}
}
/* If a square is TRACK and 2 edges are TRACK, the other two
must be NOTRACK. */
if ((state->sflags[y*w + x] & S_TRACK) &&
(S_E_COUNT(state, x, y, E_TRACK) == 2) &&
(S_E_COUNT(state, x, y, E_NOTRACK) < 2)) {
for (i = 0; i < 4; i++) {
unsigned int d = 1<<i;
if (!(S_E_FLAGS(state, x, y, d) & (E_TRACK|E_NOTRACK))) {
did += solve_set_eflag(state, x, y, d, E_NOTRACK,
"TRACK square/2 TRACK edges");
}
}
}
}
}
return did;
}