-
Notifications
You must be signed in to change notification settings - Fork 0
/
pattern.c
2374 lines (2079 loc) · 69 KB
/
pattern.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
/*
* pattern.c: the pattern-reconstruction game known as `nonograms'.
*/
#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"
enum {
COL_BACKGROUND,
COL_EMPTY,
COL_FULL,
COL_TEXT,
COL_UNKNOWN,
COL_GRID,
COL_CURSOR,
COL_ERROR,
COL_CURSOR_GUIDE,
NCOLOURS
};
#define PREFERRED_TILE_SIZE 24
#define TILE_SIZE (ds->tilesize)
#define BORDER (3 * TILE_SIZE / 4)
#define TLBORDER(d) ( (d) / 5 + 2 )
#define GUTTER (TILE_SIZE / 2)
#define FROMCOORD(d, x) \
( ((x) - (BORDER + GUTTER + TILE_SIZE * TLBORDER(d))) / TILE_SIZE )
#define SIZE(d) (2*BORDER + GUTTER + TILE_SIZE * (TLBORDER(d) + (d)))
#define GETTILESIZE(d, w) ((double)w / (2.0 + (double)TLBORDER(d) + (double)(d)))
#define TOCOORD(d, x) (BORDER + GUTTER + TILE_SIZE * (TLBORDER(d) + (x)))
struct game_params {
int w, h;
};
#define GRID_UNKNOWN 2
#define GRID_FULL 1
#define GRID_EMPTY 0
typedef struct game_state_common {
/* Parts of the game state that don't change during play. */
int w, h;
int rowsize;
int *rowdata, *rowlen;
bool *immutable;
int refcount;
enum { FS_SMALL, FS_LARGE } fontsize;
} game_state_common;
struct game_state {
game_state_common *common;
unsigned char *grid;
bool completed, cheated;
};
#define FLASH_TIME 0.13F
static game_params *default_params(void)
{
game_params *ret = snew(game_params);
ret->w = ret->h = 15;
return ret;
}
static const struct game_params pattern_presets[] = {
{10, 10},
{15, 15},
{20, 20},
#ifndef SLOW_SYSTEM
{25, 25},
{30, 30},
#endif
};
static bool game_fetch_preset(int i, char **name, game_params **params)
{
game_params *ret;
char str[80];
if (i < 0 || i >= lenof(pattern_presets))
return false;
ret = snew(game_params);
*ret = pattern_presets[i];
sprintf(str, "%dx%d", ret->w, ret->h);
*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 *ret, char const *string)
{
char const *p = string;
ret->w = atoi(p);
while (*p && isdigit((unsigned char)*p)) p++;
if (*p == 'x') {
p++;
ret->h = atoi(p);
while (*p && isdigit((unsigned char)*p)) p++;
} else {
ret->h = ret->w;
}
}
static char *encode_params(const game_params *params, bool full)
{
char ret[400];
int len;
len = sprintf(ret, "%dx%d", params->w, params->h);
assert(len < lenof(ret));
ret[len] = '\0';
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 = "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 = 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->h = atoi(cfg[1].u.string.sval);
return ret;
}
static const char *validate_params(const game_params *params, bool full)
{
if (params->w <= 0 || params->h <= 0)
return "Width and height must both be greater than zero";
if (params->w > INT_MAX - 1 || params->h > INT_MAX - 1 ||
params->w > INT_MAX / params->h)
return "Puzzle must not be unreasonably large";
if (params->w * params->h < 2)
return "Grid must contain at least two squares";
return NULL;
}
/* ----------------------------------------------------------------------
* Puzzle generation code.
*
* For this particular puzzle, it seemed important to me to ensure
* a unique solution. I do this the brute-force way, by having a
* solver algorithm alongside the generator, and repeatedly
* generating a random grid until I find one whose solution is
* unique. It turns out that this isn't too onerous on a modern PC
* provided you keep grid size below around 30. Any offers of
* better algorithms, however, will be very gratefully received.
*
* Another annoyance of this approach is that it limits the
* available puzzles to those solvable by the algorithm I've used.
* My algorithm only ever considers a single row or column at any
* one time, which means it's incapable of solving the following
* difficult example (found by Bella Image around 1995/6, when she
* and I were both doing maths degrees):
*
* 2 1 2 1
*
* +--+--+--+--+
* 1 1 | | | | |
* +--+--+--+--+
* 2 | | | | |
* +--+--+--+--+
* 1 | | | | |
* +--+--+--+--+
* 1 | | | | |
* +--+--+--+--+
*
* Obviously this cannot be solved by a one-row-or-column-at-a-time
* algorithm (it would require at least one row or column reading
* `2 1', `1 2', `3' or `4' to get started). However, it can be
* proved to have a unique solution: if the top left square were
* empty, then the only option for the top row would be to fill the
* two squares in the 1 columns, which would imply the squares
* below those were empty, leaving no place for the 2 in the second
* row. Contradiction. Hence the top left square is full, and the
* unique solution follows easily from that starting point.
*
* (The game ID for this puzzle is 4x4:2/1/2/1/1.1/2/1/1 , in case
* it's useful to anyone.)
*/
#ifndef STANDALONE_PICTURE_GENERATOR
static int float_compare(const void *av, const void *bv)
{
const float *a = (const float *)av;
const float *b = (const float *)bv;
if (*a < *b)
return -1;
else if (*a > *b)
return +1;
else
return 0;
}
static void generate(random_state *rs, int w, int h, unsigned char *retgrid)
{
float *fgrid;
float *fgrid2;
int step, i, j;
float threshold;
fgrid = snewn(w*h, float);
for (i = 0; i < h; i++) {
for (j = 0; j < w; j++) {
fgrid[i*w+j] = random_upto(rs, 100000000UL) / 100000000.F;
}
}
/*
* The above gives a completely random splattering of black and
* white cells. We want to gently bias this in favour of _some_
* reasonably thick areas of white and black, while retaining
* some randomness and fine detail.
*
* So we evolve the starting grid using a cellular automaton.
* Currently, I'm doing something very simple indeed, which is
* to set each square to the average of the surrounding nine
* cells (or the average of fewer, if we're on a corner).
*/
for (step = 0; step < 1; step++) {
fgrid2 = snewn(w*h, float);
for (i = 0; i < h; i++) {
for (j = 0; j < w; j++) {
float sx, xbar;
int n, p, q;
/*
* Compute the average of the surrounding cells.
*/
n = 0;
sx = 0.F;
for (p = -1; p <= +1; p++) {
for (q = -1; q <= +1; q++) {
if (i+p < 0 || i+p >= h || j+q < 0 || j+q >= w)
continue;
/*
* An additional special case not mentioned
* above: if a grid dimension is 2xn then
* we do not average across that dimension
* at all. Otherwise a 2x2 grid would
* contain four identical squares.
*/
if ((h==2 && p!=0) || (w==2 && q!=0))
continue;
n++;
sx += fgrid[(i+p)*w+(j+q)];
}
}
xbar = sx / n;
fgrid2[i*w+j] = xbar;
}
}
sfree(fgrid);
fgrid = fgrid2;
}
fgrid2 = snewn(w*h, float);
memcpy(fgrid2, fgrid, w*h*sizeof(float));
qsort(fgrid2, w*h, sizeof(float), float_compare);
/* Choose a threshold that makes half the pixels black. In case of
* an odd number of pixels, select randomly between just under and
* just over half. */
{
int index = w * h / 2;
if (w & h & 1)
index += random_upto(rs, 2);
if (index < w*h)
threshold = fgrid2[index];
else
threshold = fgrid2[w*h-1] + 1;
}
sfree(fgrid2);
for (i = 0; i < h; i++) {
for (j = 0; j < w; j++) {
retgrid[i*w+j] = (fgrid[i*w+j] >= threshold ? GRID_FULL :
GRID_EMPTY);
}
}
sfree(fgrid);
}
#endif
static int compute_rowdata(int *ret, unsigned char *start, int len, int step)
{
int i, n;
n = 0;
for (i = 0; i < len; i++) {
if (start[i*step] == GRID_FULL) {
int runlen = 1;
while (i+runlen < len && start[(i+runlen)*step] == GRID_FULL)
runlen++;
ret[n++] = runlen;
i += runlen;
}
if (i < len && start[i*step] == GRID_UNKNOWN)
return -1;
}
return n;
}
#define UNKNOWN 0
#define BLOCK 1
#define DOT 2
#define STILL_UNKNOWN 3
#ifdef STANDALONE_SOLVER
static bool verbose = false;
#endif
static bool do_recurse(unsigned char *known, unsigned char *deduced,
unsigned char *row,
unsigned char *minpos_done, unsigned char *maxpos_done,
unsigned char *minpos_ok, unsigned char *maxpos_ok,
int *data, int len,
int freespace, int ndone, int lowest)
{
int i, j, k;
/* This algorithm basically tries all possible ways the given rows of
* black blocks can be laid out in the row/column being examined.
* Special care is taken to avoid checking the tail of a row/column
* if the same conditions have already been checked during this recursion
* The algorithm also takes care to cut its losses as soon as an
* invalid (partial) solution is detected.
*/
if (data[ndone]) {
if (lowest >= minpos_done[ndone] && lowest <= maxpos_done[ndone]) {
if (lowest >= minpos_ok[ndone] && lowest <= maxpos_ok[ndone]) {
for (i=0; i<lowest; i++)
deduced[i] |= row[i];
}
return lowest >= minpos_ok[ndone] && lowest <= maxpos_ok[ndone];
} else {
if (lowest < minpos_done[ndone]) minpos_done[ndone] = lowest;
if (lowest > maxpos_done[ndone]) maxpos_done[ndone] = lowest;
}
for (i=0; i<=freespace; i++) {
j = lowest;
for (k=0; k<i; k++) {
if (known[j] == BLOCK) goto next_iter;
row[j++] = DOT;
}
for (k=0; k<data[ndone]; k++) {
if (known[j] == DOT) goto next_iter;
row[j++] = BLOCK;
}
if (j < len) {
if (known[j] == BLOCK) goto next_iter;
row[j++] = DOT;
}
if (do_recurse(known, deduced, row, minpos_done, maxpos_done,
minpos_ok, maxpos_ok, data, len, freespace-i, ndone+1, j)) {
if (lowest < minpos_ok[ndone]) minpos_ok[ndone] = lowest;
if (lowest + i > maxpos_ok[ndone]) maxpos_ok[ndone] = lowest + i;
if (lowest + i > maxpos_done[ndone]) maxpos_done[ndone] = lowest + i;
}
next_iter:
j++;
}
return lowest >= minpos_ok[ndone] && lowest <= maxpos_ok[ndone];
} else {
for (i=lowest; i<len; i++) {
if (known[i] == BLOCK) return false;
row[i] = DOT;
}
for (i=0; i<len; i++)
deduced[i] |= row[i];
return true;
}
}
static bool do_row(unsigned char *known, unsigned char *deduced,
unsigned char *row,
unsigned char *minpos_done, unsigned char *maxpos_done,
unsigned char *minpos_ok, unsigned char *maxpos_ok,
unsigned char *start, int len, int step, int *data,
unsigned int *changed
#ifdef STANDALONE_SOLVER
, const char *rowcol, int index, int cluewid
#endif
)
{
int rowlen, i, freespace;
bool done_any;
assert(len >= 0); /* avoid compile warnings about the memsets below */
freespace = len+1;
for (rowlen = 0; data[rowlen]; rowlen++) {
minpos_done[rowlen] = minpos_ok[rowlen] = len - 1;
maxpos_done[rowlen] = maxpos_ok[rowlen] = 0;
freespace -= data[rowlen]+1;
}
for (i = 0; i < len; i++) {
known[i] = start[i*step];
deduced[i] = 0;
}
for (i = len - 1; i >= 0 && known[i] == DOT; i--)
freespace--;
if (rowlen == 0) {
memset(deduced, DOT, len);
} else if (rowlen == 1 && data[0] == len) {
memset(deduced, BLOCK, len);
} else {
do_recurse(known, deduced, row, minpos_done, maxpos_done, minpos_ok,
maxpos_ok, data, len, freespace, 0, 0);
}
done_any = false;
for (i=0; i<len; i++)
if (deduced[i] && deduced[i] != STILL_UNKNOWN && !known[i]) {
start[i*step] = deduced[i];
if (changed) changed[i]++;
done_any = true;
}
#ifdef STANDALONE_SOLVER
if (verbose && done_any) {
char buf[80];
int thiscluewid;
printf("%s %2d: [", rowcol, index);
for (thiscluewid = -1, i = 0; data[i]; i++)
thiscluewid += sprintf(buf, " %d", data[i]);
printf("%*s", cluewid - thiscluewid, "");
for (i = 0; data[i]; i++)
printf(" %d", data[i]);
printf(" ] ");
for (i = 0; i < len; i++)
putchar(known[i] == BLOCK ? '#' :
known[i] == DOT ? '.' : '?');
printf(" -> ");
for (i = 0; i < len; i++)
putchar(start[i*step] == BLOCK ? '#' :
start[i*step] == DOT ? '.' : '?');
putchar('\n');
}
#endif
return done_any;
}
static bool solve_puzzle(const game_state *state, unsigned char *grid,
int w, int h,
unsigned char *matrix, unsigned char *workspace,
unsigned int *changed_h, unsigned int *changed_w,
int *rowdata
#ifdef STANDALONE_SOLVER
, int cluewid
#else
, int dummy
#endif
)
{
int i, j, max;
bool ok;
int max_h, max_w;
assert((state!=NULL && state->common->rowdata!=NULL) ^ (grid!=NULL));
max = max(w, h);
memset(matrix, 0, w*h);
if (state) {
for (i=0; i<w*h; i++) {
if (state->common->immutable[i])
matrix[i] = state->grid[i];
}
}
/* For each column, compute how many squares can be deduced
* from just the row-data and initial clues.
* Later, changed_* will hold how many squares were changed
* in every row/column in the previous iteration
* Changed_* is used to choose the next rows / cols to re-examine
*/
for (i=0; i<h; i++) {
int freespace, rowlen;
if (state && state->common->rowdata) {
memcpy(rowdata, state->common->rowdata + state->common->rowsize*(w+i), max*sizeof(int));
rowlen = state->common->rowlen[w+i];
} else {
rowlen = compute_rowdata(rowdata, grid+i*w, w, 1);
}
rowdata[rowlen] = 0;
if (rowlen == 0) {
changed_h[i] = w;
} else {
for (j=0, freespace=w+1; rowdata[j]; j++)
freespace -= rowdata[j] + 1;
for (j=0, changed_h[i]=0; rowdata[j]; j++)
if (rowdata[j] > freespace)
changed_h[i] += rowdata[j] - freespace;
}
for (j = 0; j < w; j++)
if (matrix[i*w+j])
changed_h[i]++;
}
for (i=0,max_h=0; i<h; i++)
if (changed_h[i] > max_h)
max_h = changed_h[i];
for (i=0; i<w; i++) {
int freespace, rowlen;
if (state && state->common->rowdata) {
memcpy(rowdata, state->common->rowdata + state->common->rowsize*i, max*sizeof(int));
rowlen = state->common->rowlen[i];
} else {
rowlen = compute_rowdata(rowdata, grid+i, h, w);
}
rowdata[rowlen] = 0;
if (rowlen == 0) {
changed_w[i] = h;
} else {
for (j=0, freespace=h+1; rowdata[j]; j++)
freespace -= rowdata[j] + 1;
for (j=0, changed_w[i]=0; rowdata[j]; j++)
if (rowdata[j] > freespace)
changed_w[i] += rowdata[j] - freespace;
}
for (j = 0; j < h; j++)
if (matrix[j*w+i])
changed_w[i]++;
}
for (i=0,max_w=0; i<w; i++)
if (changed_w[i] > max_w)
max_w = changed_w[i];
/* Solve the puzzle.
* Process rows/columns individually. Deductions involving more than one
* row and/or column at a time are not supported.
* Take care to only process rows/columns which have been changed since they
* were previously processed.
* Also, prioritize rows/columns which have had the most changes since their
* previous processing, as they promise the greatest benefit.
* Extremely rectangular grids (e.g. 10x20, 15x40, etc.) are not treated specially.
*/
do {
for (; max_h && max_h >= max_w; max_h--) {
for (i=0; i<h; i++) {
if (changed_h[i] >= max_h) {
if (state && state->common->rowdata) {
memcpy(rowdata, state->common->rowdata + state->common->rowsize*(w+i), max*sizeof(int));
rowdata[state->common->rowlen[w+i]] = 0;
} else {
rowdata[compute_rowdata(rowdata, grid+i*w, w, 1)] = 0;
}
do_row(workspace, workspace+max, workspace+2*max,
workspace+3*max, workspace+4*max,
workspace+5*max, workspace+6*max,
matrix+i*w, w, 1, rowdata, changed_w
#ifdef STANDALONE_SOLVER
, "row", i+1, cluewid
#endif
);
changed_h[i] = 0;
}
}
for (i=0,max_w=0; i<w; i++)
if (changed_w[i] > max_w)
max_w = changed_w[i];
}
for (; max_w && max_w >= max_h; max_w--) {
for (i=0; i<w; i++) {
if (changed_w[i] >= max_w) {
if (state && state->common->rowdata) {
memcpy(rowdata, state->common->rowdata + state->common->rowsize*i, max*sizeof(int));
rowdata[state->common->rowlen[i]] = 0;
} else {
rowdata[compute_rowdata(rowdata, grid+i, h, w)] = 0;
}
do_row(workspace, workspace+max, workspace+2*max,
workspace+3*max, workspace+4*max,
workspace+5*max, workspace+6*max,
matrix+i, h, w, rowdata, changed_h
#ifdef STANDALONE_SOLVER
, "col", i+1, cluewid
#endif
);
changed_w[i] = 0;
}
}
for (i=0,max_h=0; i<h; i++)
if (changed_h[i] > max_h)
max_h = changed_h[i];
}
} while (max_h>0 || max_w>0);
ok = true;
for (i=0; i<h; i++) {
for (j=0; j<w; j++) {
if (matrix[i*w+j] == UNKNOWN)
ok = false;
}
}
return ok;
}
#ifndef STANDALONE_PICTURE_GENERATOR
static unsigned char *generate_soluble(random_state *rs, int w, int h)
{
int i, j, max;
bool ok;
unsigned char *grid, *matrix, *workspace;
unsigned int *changed_h, *changed_w;
int *rowdata;
max = max(w, h);
grid = snewn(w*h, unsigned char);
/* Allocate this here, to avoid having to reallocate it again for every geneerated grid */
matrix = snewn(w*h, unsigned char);
workspace = snewn(max*7, unsigned char);
changed_h = snewn(max+1, unsigned int);
changed_w = snewn(max+1, unsigned int);
rowdata = snewn(max+1, int);
do {
generate(rs, w, h, grid);
/*
* The game is a bit too easy if any row or column is
* completely black or completely white. An exception is
* made for rows/columns that are under 3 squares,
* otherwise nothing will ever be successfully generated.
*/
ok = true;
if (w > 2) {
for (i = 0; i < h; i++) {
int colours = 0;
for (j = 0; j < w; j++)
colours |= (grid[i*w+j] == GRID_FULL ? 2 : 1);
if (colours != 3)
ok = false;
}
}
if (h > 2) {
for (j = 0; j < w; j++) {
int colours = 0;
for (i = 0; i < h; i++)
colours |= (grid[i*w+j] == GRID_FULL ? 2 : 1);
if (colours != 3)
ok = false;
}
}
if (!ok)
continue;
ok = solve_puzzle(NULL, grid, w, h, matrix, workspace,
changed_h, changed_w, rowdata, 0);
} while (!ok);
sfree(matrix);
sfree(workspace);
sfree(changed_h);
sfree(changed_w);
sfree(rowdata);
return grid;
}
#endif
#ifdef STANDALONE_PICTURE_GENERATOR
static unsigned char *picture;
#endif
static char *new_game_desc(const game_params *params, random_state *rs,
char **aux, bool interactive)
{
unsigned char *grid;
int i, j, max, rowlen, *rowdata;
char intbuf[80], *desc;
int desclen, descpos;
#ifdef STANDALONE_PICTURE_GENERATOR
game_state *state;
int *index;
#endif
max = max(params->w, params->h);
#ifdef STANDALONE_PICTURE_GENERATOR
/*
* Fixed input picture.
*/
grid = snewn(params->w * params->h, unsigned char);
memcpy(grid, picture, params->w * params->h);
/*
* Now winnow the immutable square set as far as possible.
*/
state = snew(game_state);
state->grid = grid;
state->common = snew(game_state_common);
state->common->rowdata = NULL;
state->common->immutable = snewn(params->w * params->h, bool);
for (i = 0; i < params->w * params->h; i++)
state->common->immutable[i] = true;
index = snewn(params->w * params->h, int);
for (i = 0; i < params->w * params->h; i++)
index[i] = i;
shuffle(index, params->w * params->h, sizeof(*index), rs);
{
unsigned char *matrix = snewn(params->w*params->h, unsigned char);
unsigned char *workspace = snewn(max*7, unsigned char);
unsigned int *changed_h = snewn(max+1, unsigned int);
unsigned int *changed_w = snewn(max+1, unsigned int);
int *rowdata = snewn(max+1, int);
for (i = 0; i < params->w * params->h; i++) {
state->common->immutable[index[i]] = false;
if (!solve_puzzle(state, grid, params->w, params->h,
matrix, workspace, changed_h, changed_w,
rowdata, 0))
state->common->immutable[index[i]] = true;
}
sfree(workspace);
sfree(changed_h);
sfree(changed_w);
sfree(rowdata);
sfree(matrix);
}
#else
grid = generate_soluble(rs, params->w, params->h);
#endif
rowdata = snewn(max, int);
/*
* Save the solved game in aux.
*/
if (aux) {
char *ai = snewn(params->w * params->h + 2, char);
/*
* String format is exactly the same as a solve move, so we
* can just dupstr this in solve_game().
*/
ai[0] = 'S';
for (i = 0; i < params->w * params->h; i++)
ai[i+1] = grid[i] ? '1' : '0';
ai[params->w * params->h + 1] = '\0';
*aux = ai;
}
/*
* Seed is a slash-separated list of row contents; each row
* contents section is a dot-separated list of integers. Row
* contents are listed in the order (columns left to right,
* then rows top to bottom).
*
* Simplest way to handle memory allocation is to make two
* passes, first computing the seed size and then writing it
* out.
*/
desclen = 0;
for (i = 0; i < params->w + params->h; i++) {
if (i < params->w)
rowlen = compute_rowdata(rowdata, grid+i, params->h, params->w);
else
rowlen = compute_rowdata(rowdata, grid+(i-params->w)*params->w,
params->w, 1);
if (rowlen > 0) {
for (j = 0; j < rowlen; j++) {
desclen += 1 + sprintf(intbuf, "%d", rowdata[j]);
}
} else {
desclen++;
}
}
desc = snewn(desclen, char);
descpos = 0;
for (i = 0; i < params->w + params->h; i++) {
if (i < params->w)
rowlen = compute_rowdata(rowdata, grid+i, params->h, params->w);
else
rowlen = compute_rowdata(rowdata, grid+(i-params->w)*params->w,
params->w, 1);
if (rowlen > 0) {
for (j = 0; j < rowlen; j++) {
int len = sprintf(desc+descpos, "%d", rowdata[j]);
if (j+1 < rowlen)
desc[descpos + len] = '.';
else
desc[descpos + len] = '/';
descpos += len+1;
}
} else {
desc[descpos++] = '/';
}
}
assert(descpos == desclen);
assert(desc[desclen-1] == '/');
desc[desclen-1] = '\0';
#ifdef STANDALONE_PICTURE_GENERATOR
for (i = 0; i < params->w * params->h; i++)
if (state->common->immutable[i])
break;
if (i < params->w * params->h) {
/*
* At least one immutable square, so we need a suffix.
*/
int run;
desc = sresize(desc, desclen + params->w * params->h + 3, char);
desc[descpos-1] = ',';
run = 0;
for (i = 0; i < params->w * params->h; i++) {
if (!state->common->immutable[i]) {
run++;
if (run == 25) {
desc[descpos++] = 'z';
run = 0;
}
} else {
desc[descpos++] = run + (grid[i] == GRID_FULL ? 'A' : 'a');
run = 0;
}
}
if (run > 0)
desc[descpos++] = run + 'a';
desc[descpos] = '\0';
}
sfree(state->common->immutable);
sfree(state->common);
sfree(state);
#endif
sfree(rowdata);
sfree(grid);
return desc;
}
static const char *validate_desc(const game_params *params, const char *desc)
{
int i, n, rowspace;
const char *p;
for (i = 0; i < params->w + params->h; i++) {
if (i < params->w)
rowspace = params->h + 1;
else
rowspace = params->w + 1;
if (*desc && isdigit((unsigned char)*desc)) {
do {
p = desc;
while (*desc && isdigit((unsigned char)*desc)) desc++;
n = atoi(p);
if (n <= 0)
return "all clues must be positive";
if (n > INT_MAX - 1)
return "at least one clue is grossly excessive";
rowspace -= n+1;
if (rowspace < 0) {
if (i < params->w)
return "at least one column contains more numbers than will fit";
else
return "at least one row contains more numbers than will fit";
}
} while (*desc++ == '.');
} else {
desc++; /* expect a slash immediately */
}
if (desc[-1] == '/') {
if (i+1 == params->w + params->h)
return "too many row/column specifications";
} else if (desc[-1] == '\0' || desc[-1] == ',') {
if (i+1 < params->w + params->h)
return "too few row/column specifications";
} else
return "unrecognised character in game specification";
}
if (desc[-1] == ',') {
/*
* Optional extra piece of game description which fills in
* some grid squares as extra clues.
*/
i = 0;
while (i < params->w * params->h) {
int c = (unsigned char)*desc++;
if ((c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z')) {
int len = tolower(c) - 'a';
i += len;
if (len < 25 && i < params->w*params->h)
i++;
if (i > params->w * params->h) {
return "too much data in clue-squares section";
}
} else if (!c) {
return "too little data in clue-squares section";
} else {
return "unrecognised character in clue-squares section";
}
}
if (*desc) {
return "too much data in clue-squares section";
}
}
return NULL;
}
static game_state *new_game(midend *me, const game_params *params,
const char *desc)
{
int i, j;
const char *p;
game_state *state = snew(game_state);
state->common = snew(game_state_common);
state->common->refcount = 1;
state->common->w = params->w;
state->common->h = params->h;
state->grid = snewn(state->common->w * state->common->h, unsigned char);
memset(state->grid, GRID_UNKNOWN, state->common->w * state->common->h);
state->common->immutable = snewn(state->common->w * state->common->h,
bool);
memset(state->common->immutable, 0,
state->common->w * state->common->h * sizeof(bool));
state->common->rowsize = max(state->common->w, state->common->h);
state->common->rowdata = snewn(state->common->rowsize * (state->common->w + state->common->h), int);
state->common->rowlen = snewn(state->common->w + state->common->h, int);