-
Notifications
You must be signed in to change notification settings - Fork 1
/
bridges.c
3340 lines (2914 loc) · 107 KB
/
bridges.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
/*
* bridges.c: Implementation of the Nikoli game 'Bridges'.
*
* Things still to do:
*
* - The solver's algorithmic design is not really ideal. It makes
* use of the same data representation as gameplay uses, which
* often looks like a tempting reuse of code but isn't always a
* good idea. In this case, it's unpleasant that each edge of the
* graph ends up represented as multiple squares on a grid, with
* flags indicating when edges and non-edges cross; that's useful
* when the result can be directly translated into positions of
* graphics on the display, but in purely internal work it makes
* even simple manipulations during solving more painful than they
* should be, and complex ones have no choice but to modify the
* data structures temporarily, test things, and put them back. I
* envisage a complete solver rewrite along the following lines:
* + We have a collection of vertices (islands) and edges
* (potential bridge locations, i.e. pairs of horizontal or
* vertical islands with no other island in between).
* + Each edge has an associated list of edges that cross it, and
* hence with which it is mutually exclusive.
* + For each edge, we track the min and max number of bridges we
* currently think possible.
* + For each vertex, we track the number of _liberties_ it has,
* i.e. its clue number minus the min bridge count for each edge
* out of it.
* + We also maintain a dsf that identifies sets of vertices which
* are connected components of the puzzle so far, and for each
* equivalence class we track the total number of liberties for
* that component. (The dsf mechanism will also already track
* the size of each component, i.e. number of islands.)
* + So incrementing the min for an edge requires processing along
* the lines of:
* - set the max for all edges crossing that one to zero
* - decrement the liberty count for the vertex at each end,
* and also for each vertex's equivalence class (NB they may
* be the same class)
* - unify the two equivalence classes if they're not already,
* and if so, set the liberty count for the new class to be
* the sum of the previous two.
* + Decrementing the max is much easier, however.
* + With this data structure the really fiddly stuff in stage3()
* becomes more or less trivial, because it's now a quick job to
* find out whether an island would form an isolated subgraph if
* connected to a given subset of its neighbours:
* - identify the connected components containing the test
* vertex and its putative new neighbours (but be careful not
* to count a component more than once if two or more of the
* vertices involved are already in the same one)
* - find the sum of those components' liberty counts, and also
* the total number of islands involved
* - if the total liberty count of the connected components is
* exactly equal to twice the number of edges we'd be adding
* (of course each edge destroys two liberties, one at each
* end) then these components would become a subgraph with
* zero liberties if connected together.
* - therefore, if that subgraph also contains fewer than the
* total number of islands, it's disallowed.
* - As mentioned in stage3(), once we've identified such a
* disallowed pattern, we have two choices for what to do
* with it: if the candidate set of neighbours has size 1 we
* can reduce the max for the edge to that one neighbour,
* whereas if its complement has size 1 we can increase the
* min for the edge to the _omitted_ neighbour.
*
* - write a recursive solver?
*/
#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"
#undef DRAW_GRID
/* --- structures for params, state, etc. --- */
#define MAX_BRIDGES 4
#define PREFERRED_TILE_SIZE 24
#define TILE_SIZE (ds->tilesize)
#define BORDER (TILE_SIZE / 2)
#define COORD(x) ( (x) * TILE_SIZE + BORDER )
#define FROMCOORD(x) ( ((x) - BORDER + TILE_SIZE) / TILE_SIZE - 1 )
#define FLASH_TIME 0.50F
enum {
COL_BACKGROUND,
COL_FOREGROUND,
COL_HIGHLIGHT, COL_LOWLIGHT,
COL_SELECTED, COL_MARK,
COL_HINT, COL_GRID,
COL_WARNING,
COL_CURSOR,
NCOLOURS
};
struct game_params {
int w, h, maxb;
int islands, expansion; /* %age of island squares, %age chance of expansion */
bool allowloops;
int difficulty;
};
/* general flags used by all structs */
#define G_ISLAND 0x0001
#define G_LINEV 0x0002 /* contains a vert. line */
#define G_LINEH 0x0004 /* contains a horiz. line (mutex with LINEV) */
#define G_LINE (G_LINEV|G_LINEH)
#define G_MARKV 0x0008
#define G_MARKH 0x0010
#define G_MARK (G_MARKV|G_MARKH)
#define G_NOLINEV 0x0020
#define G_NOLINEH 0x0040
#define G_NOLINE (G_NOLINEV|G_NOLINEH)
/* flags used by the error checker */
#define G_WARN 0x0080
/* flags used by the solver etc. */
#define G_SWEEP 0x1000
#define G_FLAGSH (G_LINEH|G_MARKH|G_NOLINEH)
#define G_FLAGSV (G_LINEV|G_MARKV|G_NOLINEV)
typedef unsigned int grid_type; /* change me later if we invent > 16 bits of flags. */
struct solver_state {
DSF *dsf, *tmpdsf;
int *comptspaces, *tmpcompspaces;
int refcount;
};
/* state->gridi is an optimisation; it stores the pointer to the island
* structs indexed by (x,y). It's not strictly necessary (we could use
* find234 instead), but Purify showed that board generation (mostly the solver)
* was spending 60% of its time in find234. */
struct surrounds { /* cloned from lightup.c */
struct { int x, y, dx, dy, off; } points[4];
int npoints, nislands;
};
struct island {
game_state *state;
int x, y, count;
struct surrounds adj;
};
struct game_state {
int w, h, maxb;
bool completed, solved;
bool allowloops;
grid_type *grid;
struct island *islands;
int n_islands, n_islands_alloc;
game_params params; /* used by the aux solver. */
#define N_WH_ARRAYS 5
char *wha, *possv, *possh, *lines, *maxv, *maxh;
struct island **gridi;
struct solver_state *solver; /* refcounted */
};
#define GRIDSZ(s) ((s)->w * (s)->h * sizeof(grid_type))
#define INGRID(s,x,y) ((x) >= 0 && (x) < (s)->w && (y) >= 0 && (y) < (s)->h)
#define DINDEX(x,y) ((y)*state->w + (x))
#define INDEX(s,g,x,y) ((s)->g[(y)*((s)->w) + (x)])
#define IDX(s,g,i) ((s)->g[(i)])
#define GRID(s,x,y) INDEX(s,grid,x,y)
#define POSSIBLES(s,dx,x,y) ((dx) ? (INDEX(s,possh,x,y)) : (INDEX(s,possv,x,y)))
#define MAXIMUM(s,dx,x,y) ((dx) ? (INDEX(s,maxh,x,y)) : (INDEX(s,maxv,x,y)))
#define GRIDCOUNT(s,x,y,f) ((GRID(s,x,y) & (f)) ? (INDEX(s,lines,x,y)) : 0)
#define WITHIN2(x,min,max) ((x) >= (min) && (x) <= (max))
#define WITHIN(x,min,max) ((min) > (max) ? \
WITHIN2(x,max,min) : WITHIN2(x,min,max))
/* --- island struct and tree support functions --- */
#define ISLAND_ORTH(is,j,f,df) \
(is->f + (is->adj.points[(j)].off*is->adj.points[(j)].df))
#define ISLAND_ORTHX(is,j) ISLAND_ORTH(is,j,x,dx)
#define ISLAND_ORTHY(is,j) ISLAND_ORTH(is,j,y,dy)
static void fixup_islands_for_realloc(game_state *state)
{
int i;
for (i = 0; i < state->w*state->h; i++) state->gridi[i] = NULL;
for (i = 0; i < state->n_islands; i++) {
struct island *is = &state->islands[i];
is->state = state;
INDEX(state, gridi, is->x, is->y) = is;
}
}
static bool game_can_format_as_text_now(const game_params *params)
{
return true;
}
static char *game_text_format(const game_state *state)
{
int x, y, len, nl;
char *ret, *p;
struct island *is;
grid_type grid;
len = (state->h) * (state->w+1) + 1;
ret = snewn(len, char);
p = ret;
for (y = 0; y < state->h; y++) {
for (x = 0; x < state->w; x++) {
grid = GRID(state,x,y);
nl = INDEX(state,lines,x,y);
is = INDEX(state, gridi, x, y);
if (is) {
*p++ = '0' + is->count;
} else if (grid & G_LINEV) {
*p++ = (nl > 1) ? '"' : (nl == 1) ? '|' : '!'; /* gaah, want a double-bar. */
} else if (grid & G_LINEH) {
*p++ = (nl > 1) ? '=' : (nl == 1) ? '-' : '~';
} else {
*p++ = '.';
}
}
*p++ = '\n';
}
*p++ = '\0';
assert(p - ret == len);
return ret;
}
static void debug_state(game_state *state)
{
char *textversion = game_text_format(state);
debug(("%s", textversion));
sfree(textversion);
}
/*static void debug_possibles(game_state *state)
{
int x, y;
debug(("possh followed by possv\n"));
for (y = 0; y < state->h; y++) {
for (x = 0; x < state->w; x++) {
debug(("%d", POSSIBLES(state, 1, x, y)));
}
debug((" "));
for (x = 0; x < state->w; x++) {
debug(("%d", POSSIBLES(state, 0, x, y)));
}
debug(("\n"));
}
debug(("\n"));
for (y = 0; y < state->h; y++) {
for (x = 0; x < state->w; x++) {
debug(("%d", MAXIMUM(state, 1, x, y)));
}
debug((" "));
for (x = 0; x < state->w; x++) {
debug(("%d", MAXIMUM(state, 0, x, y)));
}
debug(("\n"));
}
debug(("\n"));
}*/
static void island_set_surrounds(struct island *is)
{
assert(INGRID(is->state,is->x,is->y));
is->adj.npoints = is->adj.nislands = 0;
#define ADDPOINT(cond,ddx,ddy) do {\
if (cond) { \
is->adj.points[is->adj.npoints].x = is->x+(ddx); \
is->adj.points[is->adj.npoints].y = is->y+(ddy); \
is->adj.points[is->adj.npoints].dx = (ddx); \
is->adj.points[is->adj.npoints].dy = (ddy); \
is->adj.points[is->adj.npoints].off = 0; \
is->adj.npoints++; \
} } while(0)
ADDPOINT(is->x > 0, -1, 0);
ADDPOINT(is->x < (is->state->w-1), +1, 0);
ADDPOINT(is->y > 0, 0, -1);
ADDPOINT(is->y < (is->state->h-1), 0, +1);
}
static void island_find_orthogonal(struct island *is)
{
/* fills in the rest of the 'surrounds' structure, assuming
* all other islands are now in place. */
int i, x, y, dx, dy, off;
is->adj.nislands = 0;
for (i = 0; i < is->adj.npoints; i++) {
dx = is->adj.points[i].dx;
dy = is->adj.points[i].dy;
x = is->x + dx;
y = is->y + dy;
off = 1;
is->adj.points[i].off = 0;
while (INGRID(is->state, x, y)) {
if (GRID(is->state, x, y) & G_ISLAND) {
is->adj.points[i].off = off;
is->adj.nislands++;
/*debug(("island (%d,%d) has orth is. %d*(%d,%d) away at (%d,%d).\n",
is->x, is->y, off, dx, dy,
ISLAND_ORTHX(is,i), ISLAND_ORTHY(is,i)));*/
goto foundisland;
}
off++; x += dx; y += dy;
}
foundisland:
;
}
}
static bool island_hasbridge(struct island *is, int direction)
{
int x = is->adj.points[direction].x;
int y = is->adj.points[direction].y;
grid_type gline = is->adj.points[direction].dx ? G_LINEH : G_LINEV;
if (GRID(is->state, x, y) & gline) return true;
return false;
}
static struct island *island_find_connection(struct island *is, int adjpt)
{
struct island *is_r;
assert(adjpt < is->adj.npoints);
if (!is->adj.points[adjpt].off) return NULL;
if (!island_hasbridge(is, adjpt)) return NULL;
is_r = INDEX(is->state, gridi,
ISLAND_ORTHX(is, adjpt), ISLAND_ORTHY(is, adjpt));
assert(is_r);
return is_r;
}
static struct island *island_add(game_state *state, int x, int y, int count)
{
struct island *is;
bool realloced = false;
assert(!(GRID(state,x,y) & G_ISLAND));
GRID(state,x,y) |= G_ISLAND;
state->n_islands++;
if (state->n_islands > state->n_islands_alloc) {
state->n_islands_alloc = state->n_islands * 2;
state->islands =
sresize(state->islands, state->n_islands_alloc, struct island);
realloced = true;
}
is = &state->islands[state->n_islands-1];
memset(is, 0, sizeof(struct island));
is->state = state;
is->x = x;
is->y = y;
is->count = count;
island_set_surrounds(is);
if (realloced)
fixup_islands_for_realloc(state);
else
INDEX(state, gridi, x, y) = is;
return is;
}
/* n = -1 means 'flip NOLINE flags [and set line to 0].' */
static void island_join(struct island *i1, struct island *i2, int n, bool is_max)
{
game_state *state = i1->state;
int s, e, x, y;
assert(i1->state == i2->state);
assert(n >= -1 && n <= i1->state->maxb);
if (i1->x == i2->x) {
x = i1->x;
if (i1->y < i2->y) {
s = i1->y+1; e = i2->y-1;
} else {
s = i2->y+1; e = i1->y-1;
}
for (y = s; y <= e; y++) {
if (is_max) {
INDEX(state,maxv,x,y) = n;
} else {
if (n < 0) {
GRID(state,x,y) ^= G_NOLINEV;
} else if (n == 0) {
GRID(state,x,y) &= ~G_LINEV;
} else {
GRID(state,x,y) |= G_LINEV;
INDEX(state,lines,x,y) = n;
}
}
}
} else if (i1->y == i2->y) {
y = i1->y;
if (i1->x < i2->x) {
s = i1->x+1; e = i2->x-1;
} else {
s = i2->x+1; e = i1->x-1;
}
for (x = s; x <= e; x++) {
if (is_max) {
INDEX(state,maxh,x,y) = n;
} else {
if (n < 0) {
GRID(state,x,y) ^= G_NOLINEH;
} else if (n == 0) {
GRID(state,x,y) &= ~G_LINEH;
} else {
GRID(state,x,y) |= G_LINEH;
INDEX(state,lines,x,y) = n;
}
}
}
} else {
assert(!"island_join: islands not orthogonal.");
}
}
/* Counts the number of bridges currently attached to the island. */
static int island_countbridges(struct island *is)
{
int i, c = 0;
for (i = 0; i < is->adj.npoints; i++) {
c += GRIDCOUNT(is->state,
is->adj.points[i].x, is->adj.points[i].y,
is->adj.points[i].dx ? G_LINEH : G_LINEV);
}
/*debug(("island count for (%d,%d) is %d.\n", is->x, is->y, c));*/
return c;
}
static int island_adjspace(struct island *is, bool marks, int missing,
int direction)
{
int x, y, poss, curr, dx;
grid_type gline, mline;
x = is->adj.points[direction].x;
y = is->adj.points[direction].y;
dx = is->adj.points[direction].dx;
gline = dx ? G_LINEH : G_LINEV;
if (marks) {
mline = dx ? G_MARKH : G_MARKV;
if (GRID(is->state,x,y) & mline) return 0;
}
poss = POSSIBLES(is->state, dx, x, y);
poss = min(poss, missing);
curr = GRIDCOUNT(is->state, x, y, gline);
poss = min(poss, MAXIMUM(is->state, dx, x, y) - curr);
return poss;
}
/* Counts the number of bridge spaces left around the island;
* expects the possibles to be up-to-date. */
static int island_countspaces(struct island *is, bool marks)
{
int i, c = 0, missing;
missing = is->count - island_countbridges(is);
if (missing < 0) return 0;
for (i = 0; i < is->adj.npoints; i++) {
c += island_adjspace(is, marks, missing, i);
}
return c;
}
/* Returns a bridge count rather than a boolean */
static int island_isadj(struct island *is, int direction)
{
int x, y;
grid_type gline, mline;
x = is->adj.points[direction].x;
y = is->adj.points[direction].y;
mline = is->adj.points[direction].dx ? G_MARKH : G_MARKV;
gline = is->adj.points[direction].dx ? G_LINEH : G_LINEV;
if (GRID(is->state, x, y) & mline) {
/* If we're marked (i.e. the thing to attach to is complete)
* only count an adjacency if we're already attached. */
return GRIDCOUNT(is->state, x, y, gline);
} else {
/* If we're unmarked, count possible adjacency iff it's
* flagged as POSSIBLE. */
return POSSIBLES(is->state, is->adj.points[direction].dx, x, y);
}
return 0;
}
/* Counts the no. of possible adjacent islands (including islands
* we're already connected to). */
static int island_countadj(struct island *is)
{
int i, nadj = 0;
for (i = 0; i < is->adj.npoints; i++) {
if (island_isadj(is, i)) nadj++;
}
return nadj;
}
static void island_togglemark(struct island *is)
{
int i, j, x, y, o;
struct island *is_loop;
/* mark the island... */
GRID(is->state, is->x, is->y) ^= G_MARK;
/* ...remove all marks on non-island squares... */
for (x = 0; x < is->state->w; x++) {
for (y = 0; y < is->state->h; y++) {
if (!(GRID(is->state, x, y) & G_ISLAND))
GRID(is->state, x, y) &= ~G_MARK;
}
}
/* ...and add marks to squares around marked islands. */
for (i = 0; i < is->state->n_islands; i++) {
is_loop = &is->state->islands[i];
if (!(GRID(is_loop->state, is_loop->x, is_loop->y) & G_MARK))
continue;
for (j = 0; j < is_loop->adj.npoints; j++) {
/* if this direction takes us to another island, mark all
* squares between the two islands. */
if (!is_loop->adj.points[j].off) continue;
assert(is_loop->adj.points[j].off > 1);
for (o = 1; o < is_loop->adj.points[j].off; o++) {
GRID(is_loop->state,
is_loop->x + is_loop->adj.points[j].dx*o,
is_loop->y + is_loop->adj.points[j].dy*o) |=
is_loop->adj.points[j].dy ? G_MARKV : G_MARKH;
}
}
}
}
static bool island_impossible(struct island *is, bool strict)
{
int curr = island_countbridges(is), nspc = is->count - curr, nsurrspc;
int i, poss;
struct island *is_orth;
if (nspc < 0) {
debug(("island at (%d,%d) impossible because full.\n", is->x, is->y));
return true; /* too many bridges */
} else if ((curr + island_countspaces(is, false)) < is->count) {
debug(("island at (%d,%d) impossible because not enough spaces.\n", is->x, is->y));
return true; /* impossible to create enough bridges */
} else if (strict && curr < is->count) {
debug(("island at (%d,%d) impossible because locked.\n", is->x, is->y));
return true; /* not enough bridges and island is locked */
}
/* Count spaces in surrounding islands. */
nsurrspc = 0;
for (i = 0; i < is->adj.npoints; i++) {
int ifree, dx = is->adj.points[i].dx;
if (!is->adj.points[i].off) continue;
poss = POSSIBLES(is->state, dx,
is->adj.points[i].x, is->adj.points[i].y);
if (poss == 0) continue;
is_orth = INDEX(is->state, gridi,
ISLAND_ORTHX(is,i), ISLAND_ORTHY(is,i));
assert(is_orth);
ifree = is_orth->count - island_countbridges(is_orth);
if (ifree > 0) {
/*
* ifree is the number of bridges unfilled in the other
* island, which is clearly an upper bound on the number
* of extra bridges this island may run to it.
*
* Another upper bound is the number of bridges unfilled
* on the specific line between here and there. We must
* take the minimum of both.
*/
int bmax = MAXIMUM(is->state, dx,
is->adj.points[i].x, is->adj.points[i].y);
int bcurr = GRIDCOUNT(is->state,
is->adj.points[i].x, is->adj.points[i].y,
dx ? G_LINEH : G_LINEV);
assert(bcurr <= bmax);
nsurrspc += min(ifree, bmax - bcurr);
}
}
if (nsurrspc < nspc) {
debug(("island at (%d,%d) impossible: surr. islands %d spc, need %d.\n",
is->x, is->y, nsurrspc, nspc));
return true; /* not enough spaces around surrounding islands to fill this one. */
}
return false;
}
/* --- Game parameter functions --- */
#define DEFAULT_PRESET 0
static const struct game_params bridges_presets[] = {
{ 7, 7, 2, 30, 10, 1, 0 },
{ 7, 7, 2, 30, 10, 1, 1 },
{ 7, 7, 2, 30, 10, 1, 2 },
{ 10, 10, 2, 30, 10, 1, 0 },
{ 10, 10, 2, 30, 10, 1, 1 },
{ 10, 10, 2, 30, 10, 1, 2 },
{ 15, 15, 2, 30, 10, 1, 0 },
{ 15, 15, 2, 30, 10, 1, 1 },
{ 15, 15, 2, 30, 10, 1, 2 },
};
static game_params *default_params(void)
{
game_params *ret = snew(game_params);
*ret = bridges_presets[DEFAULT_PRESET];
return ret;
}
static bool game_fetch_preset(int i, char **name, game_params **params)
{
game_params *ret;
char buf[80];
if (i < 0 || i >= lenof(bridges_presets))
return false;
ret = default_params();
*ret = bridges_presets[i];
*params = ret;
sprintf(buf, "%dx%d %s", ret->w, ret->h,
ret->difficulty == 0 ? "easy" :
ret->difficulty == 1 ? "medium" : "hard");
*name = dupstr(buf);
return true;
}
static void free_params(game_params *params)
{
sfree(params);
}
static game_params *dup_params(const game_params *params)
{
game_params *ret = snew(game_params);
*ret = *params; /* structure copy */
return ret;
}
#define EATNUM(x) do { \
(x) = atoi(string); \
while (*string && isdigit((unsigned char)*string)) string++; \
} while(0)
static void decode_params(game_params *params, char const *string)
{
EATNUM(params->w);
params->h = params->w;
if (*string == 'x') {
string++;
EATNUM(params->h);
}
if (*string == 'i') {
string++;
EATNUM(params->islands);
}
if (*string == 'e') {
string++;
EATNUM(params->expansion);
}
if (*string == 'm') {
string++;
EATNUM(params->maxb);
}
params->allowloops = true;
if (*string == 'L') {
string++;
params->allowloops = false;
}
if (*string == 'd') {
string++;
EATNUM(params->difficulty);
}
}
static char *encode_params(const game_params *params, bool full)
{
char buf[80];
if (full) {
sprintf(buf, "%dx%di%de%dm%d%sd%d",
params->w, params->h, params->islands, params->expansion,
params->maxb, params->allowloops ? "" : "L",
params->difficulty);
} else {
sprintf(buf, "%dx%dm%d%s", params->w, params->h,
params->maxb, params->allowloops ? "" : "L");
}
return dupstr(buf);
}
static config_item *game_configure(const game_params *params)
{
config_item *ret;
char buf[80];
ret = snewn(8, 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 = ":Easy:Medium:Hard";
ret[2].u.choices.selected = params->difficulty;
ret[3].name = "Allow loops";
ret[3].type = C_BOOLEAN;
ret[3].u.boolean.bval = params->allowloops;
ret[4].name = "Max. bridges per direction";
ret[4].type = C_CHOICES;
ret[4].u.choices.choicenames = ":1:2:3:4"; /* keep up-to-date with
* MAX_BRIDGES */
ret[4].u.choices.selected = params->maxb - 1;
ret[5].name = "%age of island squares";
ret[5].type = C_CHOICES;
ret[5].u.choices.choicenames = ":5%:10%:15%:20%:25%:30%";
ret[5].u.choices.selected = (params->islands / 5)-1;
ret[6].name = "Expansion factor (%age)";
ret[6].type = C_CHOICES;
ret[6].u.choices.choicenames = ":0%:10%:20%:30%:40%:50%:60%:70%:80%:90%:100%";
ret[6].u.choices.selected = params->expansion / 10;
ret[7].name = NULL;
ret[7].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->difficulty = cfg[2].u.choices.selected;
ret->allowloops = cfg[3].u.boolean.bval;
ret->maxb = cfg[4].u.choices.selected + 1;
ret->islands = (cfg[5].u.choices.selected + 1) * 5;
ret->expansion = cfg[6].u.choices.selected * 10;
return ret;
}
static const char *validate_params(const game_params *params, bool full)
{
if (params->w < 3 || params->h < 3)
return "Width and height must be at least 3";
if (params->w > INT_MAX / params->h)
return "Width times height must not be unreasonably large";
if (params->maxb < 1 || params->maxb > MAX_BRIDGES)
return "Too many bridges.";
if (full) {
if (params->islands <= 0 || params->islands > 30)
return "%age of island squares must be between 1% and 30%";
if (params->expansion < 0 || params->expansion > 100)
return "Expansion factor must be between 0 and 100";
}
return NULL;
}
/* --- Game encoding and differences --- */
static char *encode_game(game_state *state)
{
char *ret, *p;
int wh = state->w*state->h, run, x, y;
struct island *is;
ret = snewn(wh + 1, char);
p = ret;
run = 0;
for (y = 0; y < state->h; y++) {
for (x = 0; x < state->w; x++) {
is = INDEX(state, gridi, x, y);
if (is) {
if (run) {
*p++ = ('a'-1) + run;
run = 0;
}
if (is->count < 10)
*p++ = '0' + is->count;
else
*p++ = 'A' + (is->count - 10);
} else {
if (run == 26) {
*p++ = ('a'-1) + run;
run = 0;
}
run++;
}
}
}
if (run) {
*p++ = ('a'-1) + run;
run = 0;
}
*p = '\0';
assert(p - ret <= wh);
return ret;
}
static char *game_state_diff(const game_state *src, const game_state *dest)
{
int movesize = 256, movelen = 0;
char *move = snewn(movesize, char), buf[80];
int i, d, x, y, len;
grid_type gline, nline;
struct island *is_s, *is_d, *is_orth;
#define APPEND do { \
if (movelen + len >= movesize) { \
movesize = movelen + len + 256; \
move = sresize(move, movesize, char); \
} \
strcpy(move + movelen, buf); \
movelen += len; \
} while(0)
move[movelen++] = 'S';
move[movelen] = '\0';
assert(src->n_islands == dest->n_islands);
for (i = 0; i < src->n_islands; i++) {
is_s = &src->islands[i];
is_d = &dest->islands[i];
assert(is_s->x == is_d->x);
assert(is_s->y == is_d->y);
assert(is_s->adj.npoints == is_d->adj.npoints); /* more paranoia */
for (d = 0; d < is_s->adj.npoints; d++) {
if (is_s->adj.points[d].dx == -1 ||
is_s->adj.points[d].dy == -1) continue;
x = is_s->adj.points[d].x;
y = is_s->adj.points[d].y;
gline = is_s->adj.points[d].dx ? G_LINEH : G_LINEV;
nline = is_s->adj.points[d].dx ? G_NOLINEH : G_NOLINEV;
is_orth = INDEX(dest, gridi,
ISLAND_ORTHX(is_d, d), ISLAND_ORTHY(is_d, d));
if (GRIDCOUNT(src, x, y, gline) != GRIDCOUNT(dest, x, y, gline)) {
assert(is_orth);
len = sprintf(buf, ";L%d,%d,%d,%d,%d",
is_s->x, is_s->y, is_orth->x, is_orth->y,
GRIDCOUNT(dest, x, y, gline));
APPEND;
}
if ((GRID(src,x,y) & nline) != (GRID(dest, x, y) & nline)) {
assert(is_orth);
len = sprintf(buf, ";N%d,%d,%d,%d",
is_s->x, is_s->y, is_orth->x, is_orth->y);
APPEND;
}
}
if ((GRID(src, is_s->x, is_s->y) & G_MARK) !=
(GRID(dest, is_d->x, is_d->y) & G_MARK)) {
len = sprintf(buf, ";M%d,%d", is_s->x, is_s->y);
APPEND;
}
}
return move;
}
/* --- Game setup and solving utilities --- */
/* This function is optimised; a Quantify showed that lots of grid-generation time
* (>50%) was spent in here. Hence the IDX() stuff. */
static void map_update_possibles(game_state *state)
{
int x, y, s, e, i, np, maxb, w = state->w, idx;
bool bl;
struct island *is_s = NULL, *is_f = NULL;
/* Run down vertical stripes [un]setting possv... */
for (x = 0; x < state->w; x++) {
idx = x;
s = e = -1;
bl = false;
maxb = state->params.maxb; /* placate optimiser */
/* Unset possible flags until we find an island. */
for (y = 0; y < state->h; y++) {
is_s = IDX(state, gridi, idx);
if (is_s) {
maxb = is_s->count;
break;
}
IDX(state, possv, idx) = 0;
idx += w;
}
for (; y < state->h; y++) {
maxb = min(maxb, IDX(state, maxv, idx));
is_f = IDX(state, gridi, idx);
if (is_f) {
assert(is_s);
np = min(maxb, is_f->count);
if (s != -1) {
for (i = s; i <= e; i++) {
INDEX(state, possv, x, i) = bl ? 0 : np;
}
}
s = y+1;
bl = false;
is_s = is_f;
maxb = is_s->count;
} else {
e = y;
if (IDX(state,grid,idx) & (G_LINEH|G_NOLINEV)) bl = true;
}
idx += w;
}
if (s != -1) {
for (i = s; i <= e; i++)
INDEX(state, possv, x, i) = 0;
}
}
/* ...and now do horizontal stripes [un]setting possh. */
/* can we lose this clone'n'hack? */
for (y = 0; y < state->h; y++) {
idx = y*w;
s = e = -1;
bl = false;
maxb = state->params.maxb; /* placate optimiser */
for (x = 0; x < state->w; x++) {
is_s = IDX(state, gridi, idx);
if (is_s) {
maxb = is_s->count;
break;
}
IDX(state, possh, idx) = 0;
idx += 1;
}