forked from mzucker/flow_solver
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflow_solver.c
More file actions
3032 lines (2225 loc) · 77.4 KB
/
flow_solver.c
File metadata and controls
3032 lines (2225 loc) · 77.4 KB
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
#include <stdio.h>
#include <stdint.h>
#include <locale.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
#include <math.h>
#include <time.h>
#ifndef _WIN32
#include <unistd.h>
#include <sys/time.h>
#else
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
// Positions are 8-bit integers with 4 bits each for y, x.
enum {
// Number to represent "not found"
INVALID_POS = 0xff,
// Maximum # of colors in a puzzle
MAX_COLORS = 16,
// Maximum valid size of a puzzle
MAX_SIZE = 15,
// Maximum # cells in a valid puzzle -- since we just use bit
// shifting to do x/y, need to allocate space for 1 unused column.
MAX_CELLS = (MAX_SIZE+1)*MAX_SIZE-1,
// One million(ish) bytes
MEGABYTE = 1024*1024,
};
// Various cell types, all but freespace have a color
enum {
TYPE_FREE = 0, // Free space
TYPE_PATH = 1, // Path between init & goal
TYPE_INIT = 2, // Starting point
TYPE_GOAL = 3 // Goal position
};
// Enumerate cardinal directions so we can loop over them
// RIGHT is increasing x, DOWN is increasing y.
enum {
DIR_LEFT = 0,
DIR_RIGHT = 1,
DIR_UP = 2,
DIR_DOWN = 3
};
// Search termination results
enum {
SEARCH_SUCCESS = 0,
SEARCH_UNREACHABLE = 1,
SEARCH_FULL = 2,
SEARCH_IN_PROGRESS = 3,
};
// Represent the contents of a cell on the game board
typedef uint8_t cell_t;
// Represent a position within the game board
typedef uint8_t pos_t;
// Match color characters to ANSI color codes
typedef struct color_lookup_struct {
char input_char; // Color character
char display_char; // Punctuation a la nethack
const char* ansi_code; // ANSI color code
const char* fg_rgb;
const char* bg_rgb;
} color_lookup_t;
// Options for this program
typedef struct options_struct {
int display_quiet;
int display_diagnostics;
int display_animate;
int display_color;
int display_fast;
int display_save_svg;
int node_check_touch;
int node_check_stranded;
int node_check_deadends;
int node_bottleneck_limit;
int node_penalize_exploration;
int order_autosort_colors;
int order_most_constrained;
int order_forced_first;
int order_random;
int search_best_first;
int search_outside_in;
size_t search_max_nodes;
double search_max_mb;
int search_fast_forward;
} options_t;
// Static information about a puzzle layout -- anything that does not
// change as the puzzle is solved is stored here.
typedef struct game_info_struct {
// Index in color_dict table of codes
int color_ids[MAX_COLORS];
// Color order
int color_order[MAX_COLORS];
// Initial and goal positions
pos_t init_pos[MAX_COLORS];
pos_t goal_pos[MAX_COLORS];
// Length/width of game board
size_t size;
// Number of colors present
size_t num_colors;
// Color table for looking up color ID
uint8_t color_tbl[128];
// Was user order specified?
int user_order;
} game_info_t;
// Incremental game state structure for solving -- this is what gets
// written as the search progresses, one state per search node
typedef struct game_state_struct {
// State of each cell in the world; a little wasteful to duplicate,
// since only one changes on each move, but necessary for BFS or A*
// (would not be needed for depth-first search).
cell_t cells[MAX_CELLS];
// Head position
pos_t pos[MAX_COLORS];
// How many free cells?
uint8_t num_free;
// Which was the last color / endpoint
uint8_t last_color;
// Bitflag indicating whether each color has been completed or not
// (cur_pos is adjacent to goal_pos).
uint16_t completed;
} game_state_t;
// Used for auto-sorting colors
typedef struct color_features_struct {
int index;
int user_index;
int wall_dist[2];
int min_dist;
} color_features_t;
// Disjoint-set data structure for connected component analysis of free
// space (see region_ functions).
typedef struct region_struct {
// Parent index (or INVALID_POS) if no non-free space
pos_t parent;
// Rank (see wikipedia article).
uint8_t rank;
} region_t;
// Search node for A* / BFS.
typedef struct tree_node_struct {
game_state_t state; // Current game state
double cost_to_come; // Cost to come (ignored for BFS)
double cost_to_go; // Heuristic cost (ignored for BFS)
struct tree_node_struct* parent; // Parent of this node (may be NULL)
} tree_node_t;
// Strategy is to pre-allocate a big block of nodes in advance, and
// hand them out in order.
typedef struct node_storage_struct {
tree_node_t* start; // Allocated block
size_t capacity; // How many nodes did we allocate?
size_t count; // How many did we give out?
} node_storage_t;
// Data structure for heap based priority queue
typedef struct heapq_struct {
tree_node_t** start; // Array of node pointers
size_t capacity; // Maximum allowable queue size
size_t count; // Number enqueued
} heapq_t;
// First in, first-out queue implemented as an array of pointers.
typedef struct fifo_struct {
tree_node_t** start; // Array of node pointers
size_t capacity; // Maximum number of things to enqueue ever
size_t count; // Total enqueued (next one will go into start[count])
size_t next; // Next index to dequeue
} fifo_t;
// Union struct for passing around queues.
typedef union queue_union {
heapq_t heapq;
fifo_t fifo;
} queue_t;
// Function pointers for either type of queue
queue_t (*queue_create)(size_t) = 0;
void (*queue_enqueue)(queue_t*, tree_node_t*) = 0;
tree_node_t* (*queue_deque)(queue_t*) = 0;
void (*queue_destroy)(queue_t*) = 0;
int (*queue_empty)(const queue_t*) = 0;
const tree_node_t* (*queue_peek)(const queue_t*) = 0;
//////////////////////////////////////////////////////////////////////
// For succinct printing of search results
const char SEARCH_RESULT_CHARS[4] = "suf?";
// For verbose printing of search results
const char* SEARCH_RESULT_STRINGS[4] = {
"successful",
"unsolvable",
"out of memory",
"in progress"
};
// Was gonna try some unicode magic but meh
const char* BLOCK_CHAR = "#";
// For visualizing cardinal directions ordered by the enum above.
const char DIR_CHARS[4] = "<>^v";
// x, y, pos coordinates for each direction
const int DIR_DELTA[4][3] = {
{ -1, 0, -1 },
{ 1, 0, 1 },
{ 0, -1, -16 },
{ 0, 1, 16 }
};
// Look-up table mapping characters in puzzle definitions to
// output char, ANSI color, foreground/background RGB
const color_lookup_t color_dict[MAX_COLORS] = {
{ 'R', 'o', "101", "ff0000", "723939" }, // red
{ 'B', '+', "104", "0000ff", "393972" }, // blue
{ 'Y', '@', "103", "eeee00", "6e6e39" }, // yellow
{ 'G', '*', "42", "008100", "395539" }, // green
{ 'O', 'x', "43", "ff8000", "725539" }, // orange
{ 'C', '%', "106", "00ffff", "397272" }, // cyan
{ 'M', '?', "105", "ff00ff", "723972" }, // magenta
{ 'm', 'v', "41", "a52a2a", "5f4242" }, // maroon
{ 'P', '^', "45", "800080", "553955" }, // purple
{ 'A', '=', "100", "a6a6a6", "5f5e5f" }, // gray
{ 'W', '~', "107", "ffffff", "727272" }, // white
{ 'g', '-', "102", "00ff00", "397239" }, // bright green
{ 'T', '$', "47", "bdb76b", "646251" }, // tan
{ 'b', '"', "44", "00008b", "393958" }, // dark blue
{ 'c', '&', "46", "008180", "395555" }, // dark cyan
{ 'p', '.', "35", "ff1493", "72415a" }, // pink?
};
// Global options struct gets setup during main
options_t g_options;
//////////////////////////////////////////////////////////////////////
// Return the current time as a double. Don't actually care what zero
// is cause we will just offset.
double now() {
#ifdef _WIN32
union {
LONG_LONG ns100; /*time since 1 Jan 1601 in 100ns units */
FILETIME ft;
} now;
GetSystemTimeAsFileTime (&now.ft);
return (double)now.ns100 * 1e-7; // 100 nanoseconds = 0.1 microsecond
#else
struct timeval tv;
gettimeofday(&tv, 0);
return (double)tv.tv_sec + (double)tv.tv_usec * 1e-6;
#endif
}
//////////////////////////////////////////////////////////////////////
// Peform lookup in color_dict above
int get_color_id(char c) {
for (int i=0; i<MAX_COLORS; ++i) {
if (color_dict[i].input_char == c) {
return i;
}
}
return -1;
}
//////////////////////////////////////////////////////////////////////
// Detect whether terminal supports color & cursor commands
int terminal_has_color() {
#ifdef _WIN32
return 0;
#else
if (!isatty(STDOUT_FILENO)) {
return 0;
}
char* term = getenv("TERM");
if (!term) { return 0; }
return strstr(term, "xterm") == term || strstr(term, "rxvt") == term;
#endif
}
//////////////////////////////////////////////////////////////////////
// Emit color string for index into color_dict table above
const char* color_char(const char* ansi_code, char color_out, char mono_out) {
static char buf[256];
if (g_options.display_color) {
snprintf(buf, 256, "\033[30;%sm%c\033[0m",
ansi_code, color_out);
} else {
snprintf(buf, 256, "%c", mono_out);
}
return buf;
}
//////////////////////////////////////////////////////////////////////
// Clear screen and set cursor pos to 0,0
const char* unprint_board(const game_info_t* info) {
if (g_options.display_color) {
static char buf[256];
snprintf(buf, 256, "\033[%zuA\033[%zuD",
info->size+2, info->size+2);
return buf;
} else {
return "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
}
}
//////////////////////////////////////////////////////////////////////
// Create a delay
void delay_seconds(double s) {
if (g_options.display_fast) { s /= 4.0; }
#ifdef _WIN32
// TODO: find win32 equivalent of usleep?
#else
usleep((size_t)(s * 1e6));
#endif
}
//////////////////////////////////////////////////////////////////////
// Create a 8-bit position from 2 4-bit x,y coordinates
pos_t pos_from_coords(pos_t x, pos_t y) {
return ((y & 0xf) << 4) | (x & 0xf);
}
//////////////////////////////////////////////////////////////////////
// Split 8-bit position into 4-bit x & y coords
void pos_get_coords(pos_t p, int* x, int* y) {
*x = p & 0xf;
*y = (p >> 4) & 0xf;
}
//////////////////////////////////////////////////////////////////////
// Are the coords on the map?
int coords_valid(const game_info_t* info,
int x, int y) {
return (x >= 0 && x < (int)info->size &&
y >= 0 && y < (int)info->size);
}
//////////////////////////////////////////////////////////////////////
// Compote an offset as a position and return whether valid or not
pos_t offset_pos(const game_info_t* info,
int x, int y, int dir) {
int offset_x = x + DIR_DELTA[dir][0];
int offset_y = y + DIR_DELTA[dir][1];
return coords_valid(info, offset_x, offset_y) ?
pos_from_coords(offset_x, offset_y) : INVALID_POS;
}
//////////////////////////////////////////////////////////////////////
// Compote an offset as a position and return whether valid or not
pos_t pos_offset_pos(const game_info_t* info,
pos_t pos, int dir) {
int x, y;
pos_get_coords(pos, &x, &y);
return offset_pos(info, x, y, dir);
}
//////////////////////////////////////////////////////////////////////
// Get the distance from the wall for x, y coords
int get_wall_dist(const game_info_t* info,
int x, int y) {
int p[2] = { x, y };
int d[2];
for (int i=0; i<2; ++i) {
int d0 = p[i];
int d1 = info->size - 1 - p[i];
d[i] = d0 < d1 ? d0 : d1;
}
return d[0] < d[1] ? d[0] : d[1];
}
//////////////////////////////////////////////////////////////////////
// Get the distance from the wall for 8-bit position
int pos_get_wall_dist(const game_info_t* info,
pos_t pos) {
int x, y;
pos_get_coords(pos, &x, &y);
return get_wall_dist(info, x, y);
}
//////////////////////////////////////////////////////////////////////
// Create a cell from a 2-bit type, a 4-bit color, and a 2-bit
// direction.
cell_t cell_create(uint8_t type, uint8_t color, uint8_t dir) {
return ((color & 0xf) << 4) | ((dir & 0x3) << 2) | (type & 0x3);
}
//////////////////////////////////////////////////////////////////////
// Get the type from a cell value
uint8_t cell_get_type(cell_t c) {
return c & 0x3;
}
//////////////////////////////////////////////////////////////////////
// Get the direction from a cell value
uint8_t cell_get_direction(cell_t c) {
return (c >> 2) & 0x3;
}
//////////////////////////////////////////////////////////////////////
// Get the color from a cell value
uint8_t cell_get_color(cell_t c) {
return (c >> 4) & 0xf;
}
//////////////////////////////////////////////////////////////////////
// For displaying a color nicely
const char* color_name_str(const game_info_t* info,
int color) {
const color_lookup_t* l = &color_dict[info->color_ids[color]];
return color_char(l->ansi_code, l->input_char, l->display_char);
}
//////////////////////////////////////////////////////////////////////
// For displaying a cell nicely
const char* color_cell_str(const game_info_t* info,
cell_t cell) {
int type = cell_get_type(cell);
int color = cell_get_color(cell);
int dir = cell_get_direction(cell);
const color_lookup_t* l = &color_dict[info->color_ids[color]];
switch (type) {
case TYPE_FREE:
return " ";
break;
case TYPE_PATH:
return color_char(l->ansi_code,
DIR_CHARS[dir],
l->display_char);
break;
default:
return color_char(l->ansi_code,
(type == TYPE_INIT ? 'o' : 'O'),
l->display_char);
}
}
//////////////////////////////////////////////////////////////////////
// Consider whether the given move is valid.
int game_can_move(const game_info_t* info,
const game_state_t* state,
int color, int dir) {
// Make sure color is valid
assert(color < info->num_colors);
assert(!(state->completed & (1 << color)));
// Get cur pos x, y
int cur_x, cur_y;
pos_get_coords(state->pos[color], &cur_x, &cur_y);
// Get new x, y
int new_x = cur_x + DIR_DELTA[dir][0];
int new_y = cur_y + DIR_DELTA[dir][1];
// If outside bounds, not legal
if (new_x < 0 || new_x >= info->size ||
new_y < 0 || new_y >= info->size) {
return 0;
}
// Create a new position
pos_t new_pos = pos_from_coords(new_x, new_y);
assert( new_pos < MAX_CELLS );
if (!g_options.node_check_touch &&
new_pos == info->goal_pos[color]) {
return 1;
}
// Must be empty (TYPE_FREE)
if (state->cells[new_pos]) {
return 0;
}
if (g_options.node_check_touch) {
// All puzzles are designed so that a new path segment is adjacent
// to at most one path segment of the same color -- the predecessor
// to the new segment. We check this by iterating over the
// neighbors.
for (int dir=0; dir<4; ++dir) {
// Assemble position
pos_t neighbor_pos = offset_pos(info, new_x, new_y, dir);
// If valid non-empty cell and not cur_pos and not goal_pos and
// has our color, then fail
if (neighbor_pos != INVALID_POS &&
state->cells[neighbor_pos] &&
neighbor_pos != state->pos[color] &&
neighbor_pos != info->goal_pos[color] &&
cell_get_color(state->cells[neighbor_pos]) == color) {
return 0;
}
}
}
// It's valid
return 1;
}
//////////////////////////////////////////////////////////////////////
// Print out game board as SVG
void game_print_svg(FILE* fp,
const game_info_t* info,
const game_state_t* state) {
size_t display_size = 256;
size_t m = 1;
size_t cell_size = (display_size - m * (info->size + 1)) / info->size;
int xy_skip = cell_size + m;
double dot_radius = cell_size * 0.35;
double path_radius = cell_size * 0.35;
display_size = xy_skip * info->size + m;
fprintf(fp, "<svg xmlns=\"http://www.w3.org/2000/svg\" "
"width=\"%zu\" height=\"%zu\">\n",
display_size, display_size);
fprintf(fp, " <rect width=\"%zu\" height=\"%zu\" "
"style=\"fill: #7b7c41;\" />\n",
display_size, display_size);
for (size_t y=0; y<info->size; ++y) {
size_t display_y = m+xy_skip*y;
for (size_t x=0; x<info->size; ++x) {
size_t display_x = m+xy_skip*x;
pos_t pos = pos_from_coords(x,y);
cell_t cell = state->cells[pos];
int color = cell_get_color(cell);
int type = cell_get_type(cell);
const char* cell_bg = "000000";
if (cell) {
if (type == TYPE_PATH ||
(type == TYPE_INIT) ||
(type == TYPE_GOAL && (state->completed & (1 << color)))) {
cell_bg = color_dict[info->color_ids[color]].bg_rgb;
}
}
fprintf(fp, " <rect x=\"%zu\" y=\"%zu\" "
"width=\"%zu\" height=\"%zu\" "
"style=\"fill: #%s;\" />\n",
display_x, display_y, cell_size, cell_size, cell_bg);
if (type == TYPE_INIT || type == TYPE_GOAL) {
double center_x = display_x + 0.5*cell_size;
double center_y = display_y + 0.5*cell_size;
fprintf(fp, " <circle cx=\"%g\" cy=\"%g\" "
"r=\"%g\" style=\"fill: #%s;\" />\n",
center_x, center_y, dot_radius,
color_dict[info->color_ids[color]].fg_rgb);
}
}
}
for (int color=0; color<info->num_colors; ++color) {
pos_t pos = (state->completed & (1 << color)) ?
info->goal_pos[color] : state->pos[color];
if (pos == info->init_pos[color]) { continue; }
int x, y;
pos_get_coords(pos, &x, &y);
double px = m + xy_skip*x + 0.5*cell_size;
double py = m + xy_skip*y + 0.5*cell_size;
fprintf(fp, " <path d=\"M %g,%g ", px, py);
while (1) {
cell_t cell = state->cells[pos];
assert( cell_get_color(cell) == color );
int dir = cell_get_direction(cell);
dir ^= 1; // flip direction
if (dir == DIR_LEFT || dir == DIR_RIGHT) {
fprintf(fp, "h %d ", dir == DIR_LEFT ? -xy_skip : xy_skip);
} else {
fprintf(fp, "v %d ", dir == DIR_UP ? -xy_skip : xy_skip);
}
int npos = pos_offset_pos(info, pos, dir);
if (npos == INVALID_POS) { break; }
pos = npos;
if (pos == info->init_pos[color]) {
break;
}
}
fprintf(fp, " \" style=\"stroke: #%s; stroke-width: %g; "
"fill: none; stroke-linecap: round\" />\n",
color_dict[info->color_ids[color]].fg_rgb,
path_radius);
}
fprintf(fp, "</svg>\n");
}
//////////////////////////////////////////////////////////////////////
// Thin wrapper on above.
void game_save_svg(const char* filename,
const game_info_t* info,
const game_state_t* state) {
FILE* fp = fopen(filename, "w");
if (fp) {
game_print_svg(fp, info, state);
fclose(fp);
}
}
//////////////////////////////////////////////////////////////////////
// Print out game board
void game_print(const game_info_t* info,
const game_state_t* state) {
printf("%s", BLOCK_CHAR);
for (size_t x=0; x<info->size; ++x) {
printf("%s", BLOCK_CHAR);
}
printf("%s\n", BLOCK_CHAR);
for (size_t y=0; y<info->size; ++y) {
printf("%s", BLOCK_CHAR);
for (size_t x=0; x<info->size; ++x) {
cell_t cell = state->cells[pos_from_coords(x, y)];
printf("%s", color_cell_str(info, cell));
}
printf("%s\n", BLOCK_CHAR);
}
printf("%s", BLOCK_CHAR);
for (size_t x=0; x<info->size; ++x) {
printf("%s", BLOCK_CHAR);
}
printf("%s\n", BLOCK_CHAR);
}
//////////////////////////////////////////////////////////////////////
// Return the number of free spaces around an x, y position
int game_num_free_coords(const game_info_t* info,
const game_state_t* state,
int x, int y) {
int num_free = 0;
for (int dir=0; dir<4; ++dir) {
pos_t neighbor_pos = offset_pos(info, x, y, dir);
if (neighbor_pos != INVALID_POS &&
state->cells[neighbor_pos] == 0) {
++num_free;
}
}
return num_free;
}
//////////////////////////////////////////////////////////////////////
// Return the number of free spaces around an 8-bit position
int game_num_free_pos(const game_info_t* info,
const game_state_t* state,
pos_t pos) {
int x, y;
pos_get_coords(pos, &x, &y);
return game_num_free_coords(info, state, x, y);
}
//////////////////////////////////////////////////////////////////////
// Update the game state to make the given move.
double game_make_move(const game_info_t* info,
game_state_t* state,
int color, int dir, int forced) {
// Make sure valid color
assert(color < info->num_colors);
// Update the cell with the new cell value
cell_t move = cell_create(TYPE_PATH, color, dir);
// Get current x, y
int cur_x, cur_y;
pos_get_coords(state->pos[color], &cur_x, &cur_y);
// Assemble new x, y
int new_x = cur_x + DIR_DELTA[dir][0];
int new_y = cur_y + DIR_DELTA[dir][1];
// Make sure valid
assert( new_x >= 0 && new_x < (int)info->size &&
new_y >= 0 && new_y < (int)info->size );
// Make position
pos_t new_pos = pos_from_coords(new_x, new_y);
assert( new_pos < MAX_CELLS );
if (!g_options.node_check_touch && new_pos == info->goal_pos[color]) {
state->cells[info->goal_pos[color]] = cell_create(TYPE_GOAL, color, dir);
state->completed |= 1 << color;
return 0;
}
// Make sure it's empty
assert( state->cells[new_pos] == 0 );
// Update cells and new pos
state->cells[new_pos] = move;
state->pos[color] = new_pos;
--state->num_free;
state->last_color = color;
double action_cost = 1;
int goal_dir = -1;
if (g_options.node_check_touch) {
for (int dir=0; dir<4; ++dir) {
if (offset_pos(info, new_x, new_y, dir) == info->goal_pos[color]) {
goal_dir = dir;
break;
}
}
}
if (goal_dir >= 0) {
state->cells[info->goal_pos[color]] = cell_create(TYPE_GOAL, color, goal_dir);
state->completed |= (1 << color);
action_cost = 0;
} else {
int num_free = game_num_free_coords(info, state,
new_x, new_y);
if (g_options.node_penalize_exploration && num_free == 2) {
action_cost = 2;
}
}
if (forced) {
action_cost = 0;
}
return action_cost;
}
//////////////////////////////////////////////////////////////////////
// Helper function for below.
int detect_format(FILE* fp) {
int max_letter = 'A';
int c;
while ((c = fgetc(fp)) != EOF) {
if (isalpha(c) && c > max_letter) {
max_letter = c;
}
}
rewind(fp);
return (max_letter - 'A') < MAX_COLORS;
}
//////////////////////////////////////////////////////////////////////
// Read game board from text file
int game_read(const char* filename,
game_info_t* info,
game_state_t* state) {
FILE* fp = fopen(filename, "r");
if (!fp) {
fprintf(stderr, "error opening %s\n", filename);
return 0;
}
int is_alternate_format = detect_format(fp);
memset(info, 0, sizeof(game_info_t));
memset(state, 0, sizeof(game_state_t));
memset(state->pos, 0xff, sizeof(state->pos));
state->last_color = MAX_COLORS;
size_t y=0;
char buf[MAX_SIZE+2];
memset(info->color_tbl, 0xff, sizeof(info->color_tbl));
memset(info->init_pos, 0xff, sizeof(info->init_pos));
memset(info->goal_pos, 0xff, sizeof(info->goal_pos));
while (info->size == 0 || y < info->size) {
char* s = fgets(buf, MAX_SIZE+1, fp);
size_t l = s ? strlen(s) : 0;
if (!s) {
fprintf(stderr, "%s:%zu: unexpected EOF\n", filename, y+1);
fclose(fp);
return 0;
} else if (s[l-1] != '\n') {
fprintf(stderr, "%s:%zu line too long\n", filename, y+1);
fclose(fp);
return 0;
}
if (l >= 2 && s[l-2] == '\r') { // DOS line endings
--l;
}
if (info->size == 0) {
if (l < 3) {
fprintf(stderr, "%s:1: expected at least 3 characters before newline\n",
filename);
fclose(fp);
return 0;
} else if (l-1 > MAX_SIZE) {
fprintf(stderr, "%s:1: size too big!\n", filename);
fclose(fp);
return 0;
}
info->size = l-1;
} else if (l != info->size + 1) {
fprintf(stderr, "%s:%zu: wrong number of characters before newline "
"(expected %zu, but got %zu)\n",
filename, y+1,
info->size, l-1);
fclose(fp);
return 0;
}
for (size_t x=0; x<info->size; ++x) {
uint8_t c = s[x];
if (isalpha(c)) {
pos_t pos = pos_from_coords(x, y);
assert(pos < MAX_CELLS);
int color = info->color_tbl[c];
if (color >= info->num_colors) {
color = info->num_colors;
if (info->num_colors == MAX_COLORS) {
fprintf(stderr, "%s:%zu: can't use color %c"
"- too many colors!\n",
filename, y+1, c);
fclose(fp);
return 0;
}
int id = is_alternate_format ? (c - 'A') : get_color_id(c);