-
Notifications
You must be signed in to change notification settings - Fork 1
/
inertia.c
2247 lines (1976 loc) · 56.7 KB
/
inertia.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
/*
* inertia.c: Game involving navigating round a grid picking up
* gems.
*
* Game rules and basic generator design by Ben Olmstead.
* This re-implementation was written by Simon Tatham.
*/
#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"
/* Used in the game_state */
#define BLANK 'b'
#define GEM 'g'
#define MINE 'm'
#define STOP 's'
#define WALL 'w'
/* Used in the game IDs */
#define START 'S'
/* Used in the game generation */
#define POSSGEM 'G'
/* Used only in the game_drawstate*/
#define UNDRAWN '?'
#define DIRECTIONS 8
#define DP1 (DIRECTIONS+1)
#define DX(dir) ( (dir) & 3 ? (((dir) & 7) > 4 ? -1 : +1) : 0 )
#define DY(dir) ( DX((dir)+6) )
/*
* Lvalue macro which expects x and y to be in range.
*/
#define LV_AT(w, h, grid, x, y) ( (grid)[(y)*(w)+(x)] )
/*
* Rvalue macro which can cope with x and y being out of range.
*/
#define AT(w, h, grid, x, y) ( (x)<0 || (x)>=(w) || (y)<0 || (y)>=(h) ? \
WALL : LV_AT(w, h, grid, x, y) )
enum {
COL_BACKGROUND,
COL_OUTLINE,
COL_HIGHLIGHT,
COL_LOWLIGHT,
COL_PLAYER,
COL_DEAD_PLAYER,
COL_MINE,
COL_GEM,
COL_WALL,
COL_HINT,
NCOLOURS
};
struct game_params {
int w, h;
};
typedef struct soln {
int refcount;
int len;
unsigned char *list;
} soln;
struct game_state {
game_params p;
int px, py;
int gems;
char *grid;
int distance_moved;
bool dead;
bool cheated;
int solnpos;
soln *soln;
};
static game_params *default_params(void)
{
game_params *ret = snew(game_params);
ret->w = 10;
#ifdef PORTRAIT_SCREEN
ret->h = 10;
#else
ret->h = 8;
#endif
return ret;
}
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 const struct game_params inertia_presets[] = {
#ifdef PORTRAIT_SCREEN
{ 10, 10 },
{ 12, 12 },
{ 16, 16 },
#else
{ 10, 8 },
{ 15, 12 },
{ 20, 16 },
#endif
};
static bool game_fetch_preset(int i, char **name, game_params **params)
{
game_params p, *ret;
char *retname;
char namebuf[80];
if (i < 0 || i >= lenof(inertia_presets))
return false;
p = inertia_presets[i];
ret = dup_params(&p);
sprintf(namebuf, "%dx%d", ret->w, ret->h);
retname = dupstr(namebuf);
*params = ret;
*name = retname;
return true;
}
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);
}
}
static char *encode_params(const game_params *params, bool full)
{
char data[256];
sprintf(data, "%dx%d", params->w, params->h);
return dupstr(data);
}
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)
{
/*
* Avoid completely degenerate cases which only have one
* row/column. We probably could generate completable puzzles
* of that shape, but they'd be forced to be extremely boring
* and at large sizes would take a while to happen upon at
* random as well.
*/
if (params->w < 2 || params->h < 2)
return "Width and height must both be at least two";
if (params->w > INT_MAX / params->h)
return "Width times height must not be unreasonably large";
/*
* The grid construction algorithm creates 1/5 as many gems as
* grid squares, and must create at least one gem to have an
* actual puzzle. However, an area-five grid is ruled out by
* the above constraint, so the practical minimum is six.
*/
if (params->w * params->h < 6)
return "Grid area must be at least six squares";
return NULL;
}
/* ----------------------------------------------------------------------
* Solver used by grid generator.
*/
struct solver_scratch {
bool *reachable_from, *reachable_to;
int *positions;
};
static struct solver_scratch *new_scratch(int w, int h)
{
struct solver_scratch *sc = snew(struct solver_scratch);
sc->reachable_from = snewn(w * h * DIRECTIONS, bool);
sc->reachable_to = snewn(w * h * DIRECTIONS, bool);
sc->positions = snewn(w * h * DIRECTIONS, int);
return sc;
}
static void free_scratch(struct solver_scratch *sc)
{
sfree(sc->reachable_from);
sfree(sc->reachable_to);
sfree(sc->positions);
sfree(sc);
}
static bool can_go(int w, int h, char *grid,
int x1, int y1, int dir1, int x2, int y2, int dir2)
{
/*
* Returns true if we can transition directly from (x1,y1)
* going in direction dir1, to (x2,y2) going in direction dir2.
*/
/*
* If we're actually in the middle of an unoccupyable square,
* we cannot make any move.
*/
if (AT(w, h, grid, x1, y1) == WALL ||
AT(w, h, grid, x1, y1) == MINE)
return false;
/*
* If a move is capable of stopping at x1,y1,dir1, and x2,y2 is
* the same coordinate as x1,y1, then we can make the
* transition (by stopping and changing direction).
*
* For this to be the case, we have to either have a wall
* beyond x1,y1,dir1, or have a stop on x1,y1.
*/
if (x2 == x1 && y2 == y1 &&
(AT(w, h, grid, x1, y1) == STOP ||
AT(w, h, grid, x1, y1) == START ||
AT(w, h, grid, x1+DX(dir1), y1+DY(dir1)) == WALL))
return true;
/*
* If a move is capable of continuing here, then x1,y1,dir1 can
* move one space further on.
*/
if (x2 == x1+DX(dir1) && y2 == y1+DY(dir1) && dir1 == dir2 &&
(AT(w, h, grid, x2, y2) == BLANK ||
AT(w, h, grid, x2, y2) == GEM ||
AT(w, h, grid, x2, y2) == STOP ||
AT(w, h, grid, x2, y2) == START))
return true;
/*
* That's it.
*/
return false;
}
static int find_gem_candidates(int w, int h, char *grid,
struct solver_scratch *sc)
{
int wh = w*h;
int head, tail;
int sx, sy, gx, gy, gd, pass, possgems;
/*
* This function finds all the candidate gem squares, which are
* precisely those squares which can be picked up on a loop
* from the starting point back to the starting point. Doing
* this may involve passing through such a square in the middle
* of a move; so simple breadth-first search over the _squares_
* of the grid isn't quite adequate, because it might be that
* we can only reach a gem from the start by moving over it in
* one direction, but can only return to the start if we were
* moving over it in another direction.
*
* Instead, we BFS over a space which mentions each grid square
* eight times - once for each direction. We also BFS twice:
* once to find out what square+direction pairs we can reach
* _from_ the start point, and once to find out what pairs we
* can reach the start point from. Then a square is reachable
* if any of the eight directions for that square has both
* flags set.
*/
memset(sc->reachable_from, 0, wh * DIRECTIONS * sizeof(bool));
memset(sc->reachable_to, 0, wh * DIRECTIONS * sizeof(bool));
/*
* Find the starting square.
*/
sx = -1; /* placate optimiser */
for (sy = 0; sy < h; sy++) {
for (sx = 0; sx < w; sx++)
if (AT(w, h, grid, sx, sy) == START)
break;
if (sx < w)
break;
}
assert(sy < h);
for (pass = 0; pass < 2; pass++) {
bool *reachable = (pass == 0 ? sc->reachable_from : sc->reachable_to);
int sign = (pass == 0 ? +1 : -1);
int dir;
#ifdef SOLVER_DIAGNOSTICS
printf("starting pass %d\n", pass);
#endif
/*
* `head' and `tail' are indices within sc->positions which
* track the list of board positions left to process.
*/
head = tail = 0;
for (dir = 0; dir < DIRECTIONS; dir++) {
int index = (sy*w+sx)*DIRECTIONS+dir;
sc->positions[tail++] = index;
reachable[index] = true;
#ifdef SOLVER_DIAGNOSTICS
printf("starting point %d,%d,%d\n", sx, sy, dir);
#endif
}
/*
* Now repeatedly pick an element off the list and process
* it.
*/
while (head < tail) {
int index = sc->positions[head++];
int dir = index % DIRECTIONS;
int x = (index / DIRECTIONS) % w;
int y = index / (w * DIRECTIONS);
int n, x2, y2, d2, i2;
#ifdef SOLVER_DIAGNOSTICS
printf("processing point %d,%d,%d\n", x, y, dir);
#endif
/*
* The places we attempt to switch to here are:
* - each possible direction change (all the other
* directions in this square)
* - one step further in the direction we're going (or
* one step back, if we're in the reachable_to pass).
*/
for (n = -1; n < DIRECTIONS; n++) {
if (n < 0) {
x2 = x + sign * DX(dir);
y2 = y + sign * DY(dir);
d2 = dir;
} else {
x2 = x;
y2 = y;
d2 = n;
}
i2 = (y2*w+x2)*DIRECTIONS+d2;
if (x2 >= 0 && x2 < w &&
y2 >= 0 && y2 < h &&
!reachable[i2]) {
bool ok;
#ifdef SOLVER_DIAGNOSTICS
printf(" trying point %d,%d,%d", x2, y2, d2);
#endif
if (pass == 0)
ok = can_go(w, h, grid, x, y, dir, x2, y2, d2);
else
ok = can_go(w, h, grid, x2, y2, d2, x, y, dir);
#ifdef SOLVER_DIAGNOSTICS
printf(" - %sok\n", ok ? "" : "not ");
#endif
if (ok) {
sc->positions[tail++] = i2;
reachable[i2] = true;
}
}
}
}
}
/*
* And that should be it. Now all we have to do is find the
* squares for which there exists _some_ direction such that
* the square plus that direction form a tuple which is both
* reachable from the start and reachable to the start.
*/
possgems = 0;
for (gy = 0; gy < h; gy++)
for (gx = 0; gx < w; gx++)
if (AT(w, h, grid, gx, gy) == BLANK) {
for (gd = 0; gd < DIRECTIONS; gd++) {
int index = (gy*w+gx)*DIRECTIONS+gd;
if (sc->reachable_from[index] && sc->reachable_to[index]) {
#ifdef SOLVER_DIAGNOSTICS
printf("space at %d,%d is reachable via"
" direction %d\n", gx, gy, gd);
#endif
LV_AT(w, h, grid, gx, gy) = POSSGEM;
possgems++;
break;
}
}
}
return possgems;
}
/* ----------------------------------------------------------------------
* Grid generation code.
*/
static char *gengrid(int w, int h, random_state *rs)
{
int wh = w*h;
char *grid = snewn(wh+1, char);
struct solver_scratch *sc = new_scratch(w, h);
int maxdist_threshold, tries;
maxdist_threshold = 2;
tries = 0;
while (1) {
int i, j;
int possgems;
int *dist, *list, head, tail, maxdist;
/*
* We're going to fill the grid with the five basic piece
* types in about 1/5 proportion. For the moment, though,
* we leave out the gems, because we'll put those in
* _after_ we run the solver to tell us where the viable
* locations are.
*/
i = 0;
for (j = 0; j < wh/5; j++)
grid[i++] = WALL;
for (j = 0; j < wh/5; j++)
grid[i++] = STOP;
for (j = 0; j < wh/5; j++)
grid[i++] = MINE;
assert(i < wh);
grid[i++] = START;
while (i < wh)
grid[i++] = BLANK;
shuffle(grid, wh, sizeof(*grid), rs);
/*
* Find the viable gem locations, and immediately give up
* and try again if there aren't enough of them.
*/
possgems = find_gem_candidates(w, h, grid, sc);
if (possgems < wh/5)
continue;
/*
* We _could_ now select wh/5 of the POSSGEMs and set them
* to GEM, and have a viable level. However, there's a
* chance that a large chunk of the level will turn out to
* be unreachable, so first we test for that.
*
* We do this by finding the largest distance from any
* square to the nearest POSSGEM, by breadth-first search.
* If this is above a critical threshold, we abort and try
* again.
*
* (This search is purely geometric, without regard to
* walls and long ways round.)
*/
dist = sc->positions;
list = sc->positions + wh;
for (i = 0; i < wh; i++)
dist[i] = -1;
head = tail = 0;
for (i = 0; i < wh; i++)
if (grid[i] == POSSGEM) {
dist[i] = 0;
list[tail++] = i;
}
maxdist = 0;
while (head < tail) {
int pos, x, y, d;
pos = list[head++];
if (maxdist < dist[pos])
maxdist = dist[pos];
x = pos % w;
y = pos / w;
for (d = 0; d < DIRECTIONS; d++) {
int x2, y2, p2;
x2 = x + DX(d);
y2 = y + DY(d);
if (x2 >= 0 && x2 < w && y2 >= 0 && y2 < h) {
p2 = y2*w+x2;
if (dist[p2] < 0) {
dist[p2] = dist[pos] + 1;
list[tail++] = p2;
}
}
}
}
assert(head == wh && tail == wh);
/*
* Now abandon this grid and go round again if maxdist is
* above the required threshold.
*
* We can safely start the threshold as low as 2. As we
* accumulate failed generation attempts, we gradually
* raise it as we get more desperate.
*/
if (maxdist > maxdist_threshold) {
tries++;
if (tries == 50) {
maxdist_threshold++;
tries = 0;
}
continue;
}
/*
* Now our reachable squares are plausibly evenly
* distributed over the grid. I'm not actually going to
* _enforce_ that I place the gems in such a way as not to
* increase that maxdist value; I'm now just going to trust
* to the RNG to pick a sensible subset of the POSSGEMs.
*/
j = 0;
for (i = 0; i < wh; i++)
if (grid[i] == POSSGEM)
list[j++] = i;
shuffle(list, j, sizeof(*list), rs);
for (i = 0; i < j; i++)
grid[list[i]] = (i < wh/5 ? GEM : BLANK);
break;
}
free_scratch(sc);
grid[wh] = '\0';
return grid;
}
static char *new_game_desc(const game_params *params, random_state *rs,
char **aux, bool interactive)
{
return gengrid(params->w, params->h, rs);
}
static const char *validate_desc(const game_params *params, const char *desc)
{
int w = params->w, h = params->h, wh = w*h;
int starts = 0, gems = 0, i;
for (i = 0; i < wh; i++) {
if (!desc[i])
return "Not enough data to fill grid";
if (desc[i] != WALL && desc[i] != START && desc[i] != STOP &&
desc[i] != GEM && desc[i] != MINE && desc[i] != BLANK)
return "Unrecognised character in game description";
if (desc[i] == START)
starts++;
if (desc[i] == GEM)
gems++;
}
if (desc[i])
return "Too much data to fill grid";
if (starts < 1)
return "No starting square specified";
if (starts > 1)
return "More than one starting square specified";
if (gems < 1)
return "No gems specified";
return NULL;
}
static game_state *new_game(midend *me, const game_params *params,
const char *desc)
{
int w = params->w, h = params->h, wh = w*h;
int i;
game_state *state = snew(game_state);
state->p = *params; /* structure copy */
state->grid = snewn(wh, char);
assert(strlen(desc) == wh);
memcpy(state->grid, desc, wh);
state->px = state->py = -1;
state->gems = 0;
for (i = 0; i < wh; i++) {
if (state->grid[i] == START) {
state->grid[i] = STOP;
state->px = i % w;
state->py = i / w;
} else if (state->grid[i] == GEM) {
state->gems++;
}
}
assert(state->gems > 0);
assert(state->px >= 0 && state->py >= 0);
state->distance_moved = 0;
state->dead = false;
state->cheated = false;
state->solnpos = 0;
state->soln = NULL;
return state;
}
static game_state *dup_game(const game_state *state)
{
int w = state->p.w, h = state->p.h, wh = w*h;
game_state *ret = snew(game_state);
ret->p = state->p;
ret->px = state->px;
ret->py = state->py;
ret->gems = state->gems;
ret->grid = snewn(wh, char);
ret->distance_moved = state->distance_moved;
ret->dead = false;
memcpy(ret->grid, state->grid, wh);
ret->cheated = state->cheated;
ret->soln = state->soln;
if (ret->soln)
ret->soln->refcount++;
ret->solnpos = state->solnpos;
return ret;
}
static void free_game(game_state *state)
{
if (state->soln && --state->soln->refcount == 0) {
sfree(state->soln->list);
sfree(state->soln);
}
sfree(state->grid);
sfree(state);
}
/*
* Internal function used by solver.
*/
static int move_goes_to(int w, int h, char *grid, int x, int y, int d)
{
int dr;
/*
* See where we'd get to if we made this move.
*/
dr = -1; /* placate optimiser */
while (1) {
if (AT(w, h, grid, x+DX(d), y+DY(d)) == WALL) {
dr = DIRECTIONS; /* hit a wall, so end up stationary */
break;
}
x += DX(d);
y += DY(d);
if (AT(w, h, grid, x, y) == STOP) {
dr = DIRECTIONS; /* hit a stop, so end up stationary */
break;
}
if (AT(w, h, grid, x, y) == GEM) {
dr = d; /* hit a gem, so we're still moving */
break;
}
if (AT(w, h, grid, x, y) == MINE)
return -1; /* hit a mine, so move is invalid */
}
assert(dr >= 0);
return (y*w+x)*DP1+dr;
}
static char *solve_game(const game_state *state, const game_state *currstate,
const char *aux, const char **error)
{
int w = currstate->p.w, h = currstate->p.h, wh = w*h;
int *nodes, *nodeindex, *edges, *backedges, *edgei, *backedgei, *circuit;
int nedges;
int *dist, *dist2, *list;
int *unvisited;
int circuitlen, circuitsize;
int head, tail, pass, i, j, n, x, y, d, dd;
const char *err;
char *soln, *p;
/*
* Before anything else, deal with the special case in which
* all the gems are already collected.
*/
for (i = 0; i < wh; i++)
if (currstate->grid[i] == GEM)
break;
if (i == wh) {
*error = "Game is already solved";
return NULL;
}
/*
* Solving Inertia is a question of first building up the graph
* of where you can get to from where, and secondly finding a
* tour of the graph which takes in every gem.
*
* This is of course a close cousin of the travelling salesman
* problem, which is NP-complete; so I rather doubt that any
* _optimal_ tour can be found in plausible time. Hence I'll
* restrict myself to merely finding a not-too-bad one.
*
* First construct the graph, by bfsing out move by move from
* the current player position. Graph vertices will be
* - every endpoint of a move (place the ball can be
* stationary)
* - every gem (place the ball can go through in motion).
* Vertices of this type have an associated direction, since
* if a gem can be collected by sliding through it in two
* different directions it doesn't follow that you can
* change direction at it.
*
* I'm going to refer to a non-directional vertex as
* (y*w+x)*DP1+DIRECTIONS, and a directional one as
* (y*w+x)*DP1+d.
*/
/*
* nodeindex[] maps node codes as shown above to numeric
* indices in the nodes[] array.
*/
nodeindex = snewn(DP1*wh, int);
for (i = 0; i < DP1*wh; i++)
nodeindex[i] = -1;
/*
* Do the bfs to find all the interesting graph nodes.
*/
nodes = snewn(DP1*wh, int);
head = tail = 0;
nodes[tail] = (currstate->py * w + currstate->px) * DP1 + DIRECTIONS;
nodeindex[nodes[0]] = tail;
tail++;
while (head < tail) {
int nc = nodes[head++], nnc;
d = nc % DP1;
/*
* Plot all possible moves from this node. If the node is
* directed, there's only one.
*/
for (dd = 0; dd < DIRECTIONS; dd++) {
x = nc / DP1;
y = x / w;
x %= w;
if (d < DIRECTIONS && d != dd)
continue;
nnc = move_goes_to(w, h, currstate->grid, x, y, dd);
if (nnc >= 0 && nnc != nc) {
if (nodeindex[nnc] < 0) {
nodes[tail] = nnc;
nodeindex[nnc] = tail;
tail++;
}
}
}
}
n = head;
/*
* Now we know how many nodes we have, allocate the edge array
* and go through setting up the edges.
*/
edges = snewn(DIRECTIONS*n, int);
edgei = snewn(n+1, int);
nedges = 0;
for (i = 0; i < n; i++) {
int nc = nodes[i];
edgei[i] = nedges;
d = nc % DP1;
x = nc / DP1;
y = x / w;
x %= w;
for (dd = 0; dd < DIRECTIONS; dd++) {
int nnc;
if (d >= DIRECTIONS || d == dd) {
nnc = move_goes_to(w, h, currstate->grid, x, y, dd);
if (nnc >= 0 && nnc != nc)
edges[nedges++] = nodeindex[nnc];
}
}
}
edgei[n] = nedges;
/*
* Now set up the backedges array.
*/
backedges = snewn(nedges, int);
backedgei = snewn(n+1, int);
for (i = j = 0; i < nedges; i++) {
while (j+1 < n && i >= edgei[j+1])
j++;
backedges[i] = edges[i] * n + j;
}
qsort(backedges, nedges, sizeof(int), compare_integers);
backedgei[0] = 0;
for (i = j = 0; i < nedges; i++) {
int k = backedges[i] / n;
backedges[i] %= n;
while (j < k)
backedgei[++j] = i;
}
backedgei[n] = nedges;
/*
* Set up the initial tour. At all times, our tour is a circuit
* of graph vertices (which may, and probably will often,
* repeat vertices). To begin with, it's got exactly one vertex
* in it, which is the player's current starting point.
*/
circuitsize = 256;
circuit = snewn(circuitsize, int);
circuitlen = 0;
circuit[circuitlen++] = 0; /* node index 0 is the starting posn */
/*
* Track which gems are as yet unvisited.
*/
unvisited = snewn(wh, int);
for (i = 0; i < wh; i++)
unvisited[i] = false;
for (i = 0; i < wh; i++)
if (currstate->grid[i] == GEM)
unvisited[i] = true;
/*
* Allocate space for doing bfses inside the main loop.
*/
dist = snewn(n, int);
dist2 = snewn(n, int);
list = snewn(n, int);
err = NULL;
soln = NULL;
/*
* Now enter the main loop, in each iteration of which we
* extend the tour to take in an as yet uncollected gem.
*/
while (1) {
int target, n1, n2, bestdist, extralen, targetpos;
#ifdef TSP_DIAGNOSTICS
printf("circuit is");
for (i = 0; i < circuitlen; i++) {
int nc = nodes[circuit[i]];
printf(" (%d,%d,%d)", nc/DP1%w, nc/(DP1*w), nc%DP1);
}
printf("\n");
printf("moves are ");
x = nodes[circuit[0]] / DP1 % w;
y = nodes[circuit[0]] / DP1 / w;
for (i = 1; i < circuitlen; i++) {
int x2, y2, dx, dy;
if (nodes[circuit[i]] % DP1 != DIRECTIONS)
continue;
x2 = nodes[circuit[i]] / DP1 % w;
y2 = nodes[circuit[i]] / DP1 / w;
dx = (x2 > x ? +1 : x2 < x ? -1 : 0);
dy = (y2 > y ? +1 : y2 < y ? -1 : 0);
for (d = 0; d < DIRECTIONS; d++)
if (DX(d) == dx && DY(d) == dy)
printf("%c", "89632147"[d]);
x = x2;
y = y2;
}
printf("\n");
#endif
/*
* First, start a pair of bfses at _every_ vertex currently
* in the tour, and extend them outwards to find the
* nearest as yet unreached gem vertex.
*
* This is largely a heuristic: we could pick _any_ doubly
* reachable node here and still get a valid tour as
* output. I hope that picking a nearby one will result in
* generally good tours.
*/
for (pass = 0; pass < 2; pass++) {
int *ep = (pass == 0 ? edges : backedges);
int *ei = (pass == 0 ? edgei : backedgei);
int *dp = (pass == 0 ? dist : dist2);
head = tail = 0;
for (i = 0; i < n; i++)
dp[i] = -1;
for (i = 0; i < circuitlen; i++) {
int ni = circuit[i];
if (dp[ni] < 0) {
dp[ni] = 0;
list[tail++] = ni;
}
}
while (head < tail) {
int ni = list[head++];
for (i = ei[ni]; i < ei[ni+1]; i++) {
int ti = ep[i];
if (ti >= 0 && dp[ti] < 0) {
dp[ti] = dp[ni] + 1;
list[tail++] = ti;
}
}
}
}
/* Now find the nearest unvisited gem. */
bestdist = -1;
target = -1;
for (i = 0; i < n; i++) {
if (unvisited[nodes[i] / DP1] &&
dist[i] >= 0 && dist2[i] >= 0) {
int thisdist = dist[i] + dist2[i];
if (bestdist < 0 || bestdist > thisdist) {
bestdist = thisdist;
target = i;
}
}
}
if (target < 0) {
/*
* If we get to here, we haven't found a gem we can get
* at all, which means we terminate this loop.
*/
break;
}
/*
* Now we have a graph vertex at list[tail-1] which is an
* unvisited gem. We want to add that vertex to our tour.
* So we run two more breadth-first searches: one starting
* from that vertex and following forward edges, and
* another starting from the same vertex and following