-
Notifications
You must be signed in to change notification settings - Fork 6
/
towers.c
2166 lines (1880 loc) · 53.2 KB
/
towers.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
/*
* towers.c: the puzzle also known as 'Skyscrapers'.
*
* Possible future work:
*
* - Relax the upper bound on grid size at 9?
* + I'd need TOCHAR and FROMCHAR macros a bit like group's, to
* be used wherever this code has +'0' or -'0'
* + the pencil marks in the drawstate would need a separate
* word to live in
* + the clues outside the grid would have to cope with being
* multi-digit, meaning in particular that the text formatting
* would become more unpleasant
* + most importantly, though, the solver just isn't fast
* enough. Even at size 9 it can't really do the solver_hard
* factorial-time enumeration at a sensible rate. Easy puzzles
* higher than that would be possible, but more latin-squarey
* than skyscrapery, as it were.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>
#include <math.h>
#include "puzzles.h"
#include "latin.h"
/*
* 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,solver_easy,e) \
A(HARD,Hard,solver_hard,h) \
A(EXTREME,Extreme,NULL,x) \
A(UNREASONABLE,Unreasonable,NULL,u)
#define ENUM(upper,title,func,lower) DIFF_ ## upper,
#define TITLE(upper,title,func,lower) #title,
#define ENCODE(upper,title,func,lower) #lower
#define CONFIG(upper,title,func,lower) ":" #title
enum { DIFFLIST(ENUM) DIFFCOUNT };
static char const *const towers_diffnames[] = { DIFFLIST(TITLE) };
static char const towers_diffchars[] = DIFFLIST(ENCODE);
#define DIFFCONFIG DIFFLIST(CONFIG)
enum {
COL_BACKGROUND,
COL_GRID,
COL_USER,
COL_HIGHLIGHT,
COL_ERROR,
COL_PENCIL,
COL_DONE,
NCOLOURS
};
struct game_params {
int w, diff;
};
struct clues {
int refcount;
int w;
/*
* An array of 4w integers, of which:
* - the first w run across the top
* - the next w across the bottom
* - the third w down the left
* - the last w down the right.
*/
int *clues;
/*
* An array of w*w digits.
*/
digit *immutable;
};
/*
* Macros to compute clue indices and coordinates.
*/
#define STARTSTEP(start, step, index, w) do { \
if (index < w) \
start = index, step = w; \
else if (index < 2*w) \
start = (w-1)*w+(index-w), step = -w; \
else if (index < 3*w) \
start = w*(index-2*w), step = 1; \
else \
start = w*(index-3*w)+(w-1), step = -1; \
} while (0)
#define CSTARTSTEP(start, step, index, w) \
STARTSTEP(start, step, (((index)+2*w)%(4*w)), w)
#define CLUEPOS(x, y, index, w) do { \
if (index < w) \
x = index, y = -1; \
else if (index < 2*w) \
x = index-w, y = w; \
else if (index < 3*w) \
x = -1, y = index-2*w; \
else \
x = w, y = index-3*w; \
} while (0)
#ifdef STANDALONE_SOLVER
static const char *const cluepos[] = {
"above column", "below column", "left of row", "right of row"
};
#endif
struct game_state {
game_params par;
struct clues *clues;
bool *clues_done;
digit *grid;
int *pencil; /* bitmaps using bits 1<<1..1<<n */
bool completed, cheated;
};
static game_params *default_params(void)
{
game_params *ret = snew(game_params);
ret->w = 5;
ret->diff = DIFF_EASY;
return ret;
}
static const struct game_params towers_presets[] = {
{ 4, DIFF_EASY },
{ 5, DIFF_EASY },
{ 5, DIFF_HARD },
{ 6, DIFF_EASY },
{ 6, DIFF_HARD },
{ 6, DIFF_EXTREME },
{ 6, DIFF_UNREASONABLE },
};
static bool game_fetch_preset(int i, char **name, game_params **params)
{
game_params *ret;
char buf[80];
if (i < 0 || i >= lenof(towers_presets))
return false;
ret = snew(game_params);
*ret = towers_presets[i]; /* structure copy */
sprintf(buf, "%dx%d %s", ret->w, ret->w, towers_diffnames[ret->diff]);
*name = dupstr(buf);
*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)
{
char const *p = string;
params->w = atoi(p);
while (*p && isdigit((unsigned char)*p)) p++;
if (*p == 'd') {
int i;
p++;
params->diff = DIFFCOUNT+1; /* ...which is invalid */
if (*p) {
for (i = 0; i < DIFFCOUNT; i++) {
if (*p == towers_diffchars[i])
params->diff = i;
}
p++;
}
}
}
static char *encode_params(const game_params *params, bool full)
{
char ret[80];
sprintf(ret, "%d", params->w);
if (full)
sprintf(ret + strlen(ret), "d%c", towers_diffchars[params->diff]);
return dupstr(ret);
}
static config_item *game_configure(const game_params *params)
{
config_item *ret;
char buf[80];
ret = snewn(3, config_item);
ret[0].name = "Grid size";
ret[0].type = C_STRING;
sprintf(buf, "%d", params->w);
ret[0].u.string.sval = dupstr(buf);
ret[1].name = "Difficulty";
ret[1].type = C_CHOICES;
ret[1].u.choices.choicenames = DIFFCONFIG;
ret[1].u.choices.selected = params->diff;
ret[2].name = NULL;
ret[2].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->diff = cfg[1].u.choices.selected;
return ret;
}
static const char *validate_params(const game_params *params, bool full)
{
if (params->w < 3 || params->w > 9)
return "Grid size must be between 3 and 9";
if (params->diff >= DIFFCOUNT)
return "Unknown difficulty rating";
return NULL;
}
/* ----------------------------------------------------------------------
* Solver.
*/
struct solver_ctx {
int w, diff;
bool started;
int *clues;
long *iscratch;
int *dscratch;
};
static int solver_easy(struct latin_solver *solver, void *vctx)
{
struct solver_ctx *ctx = (struct solver_ctx *)vctx;
int w = ctx->w;
int c, i, j, n, m, furthest;
int start, step, cstart, cstep, clue, pos, cpos;
int ret = 0;
#ifdef STANDALONE_SOLVER
char prefix[256];
#endif
if (!ctx->started) {
ctx->started = true;
/*
* One-off loop to help get started: when a pair of facing
* clues sum to w+1, it must mean that the row consists of
* two increasing sequences back to back, so we can
* immediately place the highest digit by knowing the
* lengths of those two sequences.
*/
for (c = 0; c < 3*w; c = (c == w-1 ? 2*w : c+1)) {
int c2 = c + w;
if (ctx->clues[c] && ctx->clues[c2] &&
ctx->clues[c] + ctx->clues[c2] == w+1) {
STARTSTEP(start, step, c, w);
CSTARTSTEP(cstart, cstep, c, w);
pos = start + (ctx->clues[c]-1)*step;
cpos = cstart + (ctx->clues[c]-1)*cstep;
if (solver->cube[cpos*w+w-1]) {
#ifdef STANDALONE_SOLVER
if (solver_show_working) {
printf("%*sfacing clues on %s %d are maximal:\n",
solver_recurse_depth*4, "",
c>=2*w ? "row" : "column", c % w + 1);
printf("%*s placing %d at (%d,%d)\n",
solver_recurse_depth*4, "",
w, pos%w+1, pos/w+1);
}
#endif
latin_solver_place(solver, pos%w, pos/w, w);
ret = 1;
} else {
ret = -1;
}
}
}
if (ret)
return ret;
}
/*
* Go over every clue doing reasonably simple heuristic
* deductions.
*/
for (c = 0; c < 4*w; c++) {
clue = ctx->clues[c];
if (!clue)
continue;
STARTSTEP(start, step, c, w);
CSTARTSTEP(cstart, cstep, c, w);
/* Find the location of each number in the row. */
for (i = 0; i < w; i++)
ctx->dscratch[i] = w;
for (i = 0; i < w; i++)
if (solver->grid[start+i*step])
ctx->dscratch[solver->grid[start+i*step]-1] = i;
n = m = 0;
furthest = w;
for (i = w; i >= 1; i--) {
if (ctx->dscratch[i-1] == w) {
break;
} else if (ctx->dscratch[i-1] < furthest) {
furthest = ctx->dscratch[i-1];
m = i;
n++;
}
}
if (clue == n+1 && furthest > 1) {
#ifdef STANDALONE_SOLVER
if (solver_show_working)
sprintf(prefix, "%*sclue %s %d is nearly filled:\n",
solver_recurse_depth*4, "",
cluepos[c/w], c%w+1);
else
prefix[0] = '\0'; /* placate optimiser */
#endif
/*
* We can already see an increasing sequence of the very
* highest numbers, of length one less than that
* specified in the clue. All of those numbers _must_ be
* part of the clue sequence, so the number right next
* to the clue must be the final one - i.e. it must be
* bigger than any of the numbers between it and m. This
* allows us to rule out small numbers in that square.
*
* (This is a generalisation of the obvious deduction
* that when you see a clue saying 1, it must be right
* next to the largest possible number; and similarly,
* when you see a clue saying 2 opposite that, it must
* be right next to the second-largest.)
*/
j = furthest-1; /* number of small numbers we can rule out */
for (i = 1; i <= w && j > 0; i++) {
if (ctx->dscratch[i-1] < w && ctx->dscratch[i-1] >= furthest)
continue; /* skip this number, it's elsewhere */
j--;
if (solver->cube[cstart*w+i-1]) {
#ifdef STANDALONE_SOLVER
if (solver_show_working) {
printf("%s%*s ruling out %d at (%d,%d)\n",
prefix, solver_recurse_depth*4, "",
i, start%w+1, start/w+1);
prefix[0] = '\0';
}
#endif
solver->cube[cstart*w+i-1] = 0;
ret = 1;
}
}
}
if (ret)
return ret;
#ifdef STANDALONE_SOLVER
if (solver_show_working)
sprintf(prefix, "%*slower bounds for clue %s %d:\n",
solver_recurse_depth*4, "",
cluepos[c/w], c%w+1);
else
prefix[0] = '\0'; /* placate optimiser */
#endif
i = 0;
for (n = w; n > 0; n--) {
/*
* The largest number cannot occur in the first (clue-1)
* squares of the row, or else there wouldn't be space
* for a sufficiently long increasing sequence which it
* terminated. The second-largest number (not counting
* any that are known to be on the far side of a larger
* number and hence excluded from this sequence) cannot
* occur in the first (clue-2) squares, similarly, and
* so on.
*/
if (ctx->dscratch[n-1] < w) {
for (m = n+1; m < w; m++)
if (ctx->dscratch[m] < ctx->dscratch[n-1])
break;
if (m < w)
continue; /* this number doesn't count */
}
for (j = 0; j < clue - i - 1; j++)
if (solver->cube[(cstart + j*cstep)*w+n-1]) {
#ifdef STANDALONE_SOLVER
if (solver_show_working) {
int pos = start+j*step;
printf("%s%*s ruling out %d at (%d,%d)\n",
prefix, solver_recurse_depth*4, "",
n, pos%w+1, pos/w+1);
prefix[0] = '\0';
}
#endif
solver->cube[(cstart + j*cstep)*w+n-1] = 0;
ret = 1;
}
i++;
}
}
if (ret)
return ret;
return 0;
}
static int solver_hard(struct latin_solver *solver, void *vctx)
{
struct solver_ctx *ctx = (struct solver_ctx *)vctx;
int w = ctx->w;
int c, i, j, n, best, clue, start, step, ret;
long bitmap;
#ifdef STANDALONE_SOLVER
char prefix[256];
#endif
/*
* Go over every clue analysing all possibilities.
*/
for (c = 0; c < 4*w; c++) {
clue = ctx->clues[c];
if (!clue)
continue;
CSTARTSTEP(start, step, c, w);
for (i = 0; i < w; i++)
ctx->iscratch[i] = 0;
/*
* Instead of a tedious physical recursion, I iterate in the
* scratch array through all possibilities. At any given
* moment, i indexes the element of the box that will next
* be incremented.
*/
i = 0;
ctx->dscratch[i] = 0;
best = n = 0;
bitmap = 0;
while (1) {
if (i < w) {
/*
* Find the next valid value for cell i.
*/
int limit = (n == clue ? best : w);
int pos = start + step * i;
for (j = ctx->dscratch[i] + 1; j <= limit; j++) {
if (bitmap & (1L << j))
continue; /* used this one already */
if (!solver->cube[pos*w+j-1])
continue; /* ruled out already */
/* Found one. */
break;
}
if (j > limit) {
/* No valid values left; drop back. */
i--;
if (i < 0)
break; /* overall iteration is finished */
bitmap &= ~(1L << ctx->dscratch[i]);
if (ctx->dscratch[i] == best) {
n--;
best = 0;
for (j = 0; j < i; j++)
if (best < ctx->dscratch[j])
best = ctx->dscratch[j];
}
} else {
/* Got a valid value; store it and move on. */
bitmap |= 1L << j;
ctx->dscratch[i++] = j;
if (j > best) {
best = j;
n++;
}
ctx->dscratch[i] = 0;
}
} else {
if (n == clue) {
for (j = 0; j < w; j++)
ctx->iscratch[j] |= 1L << ctx->dscratch[j];
}
i--;
bitmap &= ~(1L << ctx->dscratch[i]);
if (ctx->dscratch[i] == best) {
n--;
best = 0;
for (j = 0; j < i; j++)
if (best < ctx->dscratch[j])
best = ctx->dscratch[j];
}
}
}
#ifdef STANDALONE_SOLVER
if (solver_show_working)
sprintf(prefix, "%*sexhaustive analysis of clue %s %d:\n",
solver_recurse_depth*4, "",
cluepos[c/w], c%w+1);
else
prefix[0] = '\0'; /* placate optimiser */
#endif
ret = 0;
for (i = 0; i < w; i++) {
int pos = start + step * i;
for (j = 1; j <= w; j++) {
if (solver->cube[pos*w+j-1] &&
!(ctx->iscratch[i] & (1L << j))) {
#ifdef STANDALONE_SOLVER
if (solver_show_working) {
printf("%s%*s ruling out %d at (%d,%d)\n",
prefix, solver_recurse_depth*4, "",
j, pos/w+1, pos%w+1);
prefix[0] = '\0';
}
#endif
solver->cube[pos*w+j-1] = 0;
ret = 1;
}
}
/*
* Once we find one clue we can do something with in
* this way, revert to trying easier deductions, so as
* not to generate solver diagnostics that make the
* problem look harder than it is.
*/
if (ret)
return ret;
}
}
return 0;
}
#define SOLVER(upper,title,func,lower) func,
static usersolver_t const towers_solvers[] = { DIFFLIST(SOLVER) };
static bool towers_valid(struct latin_solver *solver, void *vctx)
{
struct solver_ctx *ctx = (struct solver_ctx *)vctx;
int w = ctx->w;
int c, i, n, best, clue, start, step;
for (c = 0; c < 4*w; c++) {
clue = ctx->clues[c];
if (!clue)
continue;
STARTSTEP(start, step, c, w);
n = best = 0;
for (i = 0; i < w; i++) {
if (solver->grid[start+i*step] > best) {
best = solver->grid[start+i*step];
n++;
}
}
if (n != clue) {
#ifdef STANDALONE_SOLVER
if (solver_show_working)
printf("%*sclue %s %d is violated\n",
solver_recurse_depth*4, "",
cluepos[c/w], c%w+1);
#endif
return false;
}
}
return true;
}
static int solver(int w, int *clues, digit *soln, int maxdiff)
{
int ret;
struct solver_ctx ctx;
ctx.w = w;
ctx.diff = maxdiff;
ctx.clues = clues;
ctx.started = false;
ctx.iscratch = snewn(w, long);
ctx.dscratch = snewn(w+1, int);
ret = latin_solver(soln, w, maxdiff,
DIFF_EASY, DIFF_HARD, DIFF_EXTREME,
DIFF_EXTREME, DIFF_UNREASONABLE,
towers_solvers, towers_valid, &ctx, NULL, NULL);
sfree(ctx.iscratch);
sfree(ctx.dscratch);
return ret;
}
/* ----------------------------------------------------------------------
* Grid generation.
*/
static char *new_game_desc(const game_params *params, random_state *rs,
char **aux, bool interactive)
{
int w = params->w, a = w*w;
digit *grid, *soln, *soln2;
int *clues, *order;
int i, ret;
int diff = params->diff;
char *desc, *p;
/*
* Difficulty exceptions: some combinations of size and
* difficulty cannot be satisfied, because all puzzles of at
* most that difficulty are actually even easier.
*
* Remember to re-test this whenever a change is made to the
* solver logic!
*
* I tested it using the following shell command:
for d in e h x u; do
for i in {3..9}; do
echo -n "./towers --generate 1 ${i}d${d}: "
perl -e 'alarm 30; exec @ARGV' ./towers --generate 1 ${i}d${d} >/dev/null \
&& echo ok
done
done
* Of course, it's better to do that after taking the exceptions
* _out_, so as to detect exceptions that should be removed as
* well as those which should be added.
*/
if (diff > DIFF_HARD && w <= 3)
diff = DIFF_HARD;
grid = NULL;
clues = snewn(4*w, int);
soln = snewn(a, digit);
soln2 = snewn(a, digit);
order = snewn(max(4*w,a), int);
while (1) {
/*
* Construct a latin square to be the solution.
*/
sfree(grid);
grid = latin_generate(w, rs);
/*
* Fill in the clues.
*/
for (i = 0; i < 4*w; i++) {
int start, step, j, k, best;
STARTSTEP(start, step, i, w);
k = best = 0;
for (j = 0; j < w; j++) {
if (grid[start+j*step] > best) {
best = grid[start+j*step];
k++;
}
}
clues[i] = k;
}
/*
* Remove the grid numbers and then the clues, one by one,
* for as long as the game remains soluble at the given
* difficulty.
*/
memcpy(soln, grid, a);
if (diff == DIFF_EASY && w <= 5) {
/*
* Special case: for Easy-mode grids that are small
* enough, it's nice to be able to find completely empty
* grids.
*/
memset(soln2, 0, a);
ret = solver(w, clues, soln2, diff);
if (ret > diff)
continue;
}
for (i = 0; i < a; i++)
order[i] = i;
shuffle(order, a, sizeof(*order), rs);
for (i = 0; i < a; i++) {
int j = order[i];
memcpy(soln2, grid, a);
soln2[j] = 0;
ret = solver(w, clues, soln2, diff);
if (ret <= diff)
grid[j] = 0;
}
if (diff > DIFF_EASY) { /* leave all clues on Easy mode */
for (i = 0; i < 4*w; i++)
order[i] = i;
shuffle(order, 4*w, sizeof(*order), rs);
for (i = 0; i < 4*w; i++) {
int j = order[i];
int clue = clues[j];
memcpy(soln2, grid, a);
clues[j] = 0;
ret = solver(w, clues, soln2, diff);
if (ret > diff)
clues[j] = clue;
}
}
/*
* See if the game can be solved at the specified difficulty
* level, but not at the one below.
*/
memcpy(soln2, grid, a);
ret = solver(w, clues, soln2, diff);
if (ret != diff)
continue; /* go round again */
/*
* We've got a usable puzzle!
*/
break;
}
/*
* Encode the puzzle description.
*/
desc = snewn(40*a, char);
p = desc;
for (i = 0; i < 4*w; i++) {
if (i)
*p++ = '/';
if (clues[i])
p += sprintf(p, "%d", clues[i]);
}
for (i = 0; i < a; i++)
if (grid[i])
break;
if (i < a) {
int run = 0;
*p++ = ',';
for (i = 0; i <= a; i++) {
int n = (i < a ? grid[i] : -1);
if (!n)
run++;
else {
if (run) {
while (run > 0) {
int thisrun = min(run, 26);
*p++ = thisrun - 1 + 'a';
run -= thisrun;
}
} else {
/*
* If there's a number in the very top left or
* bottom right, there's no point putting an
* unnecessary _ before or after it.
*/
if (i > 0 && n > 0)
*p++ = '_';
}
if (n > 0)
p += sprintf(p, "%d", n);
run = 0;
}
}
}
*p++ = '\0';
desc = sresize(desc, p - desc, char);
/*
* Encode the solution.
*/
*aux = snewn(a+2, char);
(*aux)[0] = 'S';
for (i = 0; i < a; i++)
(*aux)[i+1] = '0' + soln[i];
(*aux)[a+1] = '\0';
sfree(grid);
sfree(clues);
sfree(soln);
sfree(soln2);
sfree(order);
return desc;
}
/* ----------------------------------------------------------------------
* Gameplay.
*/
static const char *validate_desc(const game_params *params, const char *desc)
{
int w = params->w, a = w*w;
const char *p = desc;
int i, clue;
/*
* Verify that the right number of clues are given, and that
* they're in range.
*/
for (i = 0; i < 4*w; i++) {
if (!*p)
return "Too few clues for grid size";
if (i > 0) {
if (*p != '/')
return "Expected commas between clues";
p++;
}
if (isdigit((unsigned char)*p)) {
clue = atoi(p);
while (*p && isdigit((unsigned char)*p)) p++;
if (clue <= 0 || clue > w)
return "Clue number out of range";
}
}
if (*p == '/')
return "Too many clues for grid size";
if (*p == ',') {
/*
* Verify that the right amount of grid data is given, and
* that any grid elements provided are in range.
*/
int squares = 0;
p++;
while (*p) {
int c = *p++;
if (c >= 'a' && c <= 'z') {
squares += c - 'a' + 1;
} else if (c == '_') {
/* do nothing */;
} else if (c > '0' && c <= '9') {
int val = atoi(p-1);
if (val < 1 || val > w)
return "Out-of-range number in grid description";
squares++;
while (*p && isdigit((unsigned char)*p)) p++;
} else
return "Invalid character in game description";
}
if (squares < a)
return "Not enough data to fill grid";
if (squares > a)
return "Too much data to fit in grid";
}
return NULL;
}
static key_label *game_request_keys(const game_params *params, int *nkeys)
{
int i;
int w = params->w;
key_label *keys = snewn(w+1, key_label);
*nkeys = w + 1;
for (i = 0; i < w; i++) {
if (i<9) keys[i].button = '1' + i;
else keys[i].button = 'a' + i - 9;
keys[i].label = NULL;
}
keys[w].button = '\b';
keys[w].label = NULL;
return keys;
}
static game_state *new_game(midend *me, const game_params *params,
const char *desc)
{
int w = params->w, a = w*w;
game_state *state = snew(game_state);
const char *p = desc;
int i;
state->par = *params; /* structure copy */
state->clues = snew(struct clues);
state->clues->refcount = 1;
state->clues->w = w;
state->clues->clues = snewn(4*w, int);
state->clues->immutable = snewn(a, digit);
state->grid = snewn(a, digit);
state->clues_done = snewn(4*w, bool);
state->pencil = snewn(a, int);
for (i = 0; i < a; i++) {
state->grid[i] = 0;
state->pencil[i] = 0;
}
memset(state->clues->immutable, 0, a);
memset(state->clues_done, 0, 4*w*sizeof(bool));
for (i = 0; i < 4*w; i++) {
if (i > 0) {
assert(*p == '/');
p++;
}
if (*p && isdigit((unsigned char)*p)) {
state->clues->clues[i] = atoi(p);
while (*p && isdigit((unsigned char)*p)) p++;
} else
state->clues->clues[i] = 0;
}
if (*p == ',') {
int pos = 0;
p++;
while (*p) {
int c = *p++;
if (c >= 'a' && c <= 'z') {
pos += c - 'a' + 1;
} else if (c == '_') {
/* do nothing */;
} else if (c > '0' && c <= '9') {
int val = atoi(p-1);
assert(val >= 1 && val <= w);
assert(pos < a);
state->grid[pos] = state->clues->immutable[pos] = val;
pos++;
while (*p && isdigit((unsigned char)*p)) p++;
} else
assert(!"Corrupt game description");
}
assert(pos == a);
}
assert(!*p);
state->completed = false;
state->cheated = false;
return state;
}
static game_state *dup_game(const game_state *state)
{
int w = state->par.w, a = w*w;
game_state *ret = snew(game_state);
ret->par = state->par; /* structure copy */
ret->clues = state->clues;
ret->clues->refcount++;
ret->grid = snewn(a, digit);
ret->pencil = snewn(a, int);
ret->clues_done = snewn(4*w, bool);
memcpy(ret->grid, state->grid, a*sizeof(digit));
memcpy(ret->pencil, state->pencil, a*sizeof(int));
memcpy(ret->clues_done, state->clues_done, 4*w*sizeof(bool));