-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathagent.c
More file actions
611 lines (539 loc) · 19.2 KB
/
agent.c
File metadata and controls
611 lines (539 loc) · 19.2 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
// AI agent for solving mine.pas
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdarg.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <unistd.h>
#include <sys/wait.h>
#include <termios.h>
#include <poll.h>
#define shift(xs, xs_sz) (assert((xs_sz) > 0), (xs_sz)--, *(xs)++)
#if defined(__GNUC__) || defined(__clang__)
// https://gcc.gnu.org/onlinedocs/gcc-4.7.2/gcc/Function-Attributes.html
# ifdef __MINGW_PRINTF_FORMAT
# define PRINTF_FORMAT(STRING_INDEX, FIRST_TO_CHECK) __attribute__ ((format (__MINGW_PRINTF_FORMAT, STRING_INDEX, FIRST_TO_CHECK)))
# else
# define PRINTF_FORMAT(STRING_INDEX, FIRST_TO_CHECK) __attribute__ ((format (printf, STRING_INDEX, FIRST_TO_CHECK)))
# endif // __MINGW_PRINTF_FORMAT
#else
// TODO: implement PRINTF_FORMAT for MSVC
# define PRINTF_FORMAT(STRING_INDEX, FIRST_TO_CHECK)
#endif
#define UNREACHABLE(...) panic(__FILE__, __LINE__, "UNREACHABLE", __VA_ARGS__)
void panic(const char *file, int line, const char *label, const char *fmt, ...) PRINTF_FORMAT(4, 5);
void panic(const char *file, int line, const char *label, const char *fmt, ...)
{
fprintf(stderr, "%s:%d: %s: ", file, line, label);
va_list args;
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
fprintf(stderr, "\n");
abort();
}
typedef struct {
char *items;
size_t count;
size_t capacity;
} String_Builder;
#define sb_append da_append
#define sb_to_sv(sb) ((String_View) { .data = (sb).items, .count = (sb).count })
#define DA_INIT_CAP 256
#define da_reserve(da, expected_capacity) \
do { \
if ((expected_capacity) > (da)->capacity) { \
if ((da)->capacity == 0) { \
(da)->capacity = DA_INIT_CAP; \
} \
while ((expected_capacity) > (da)->capacity) { \
(da)->capacity *= 2; \
} \
(da)->items = realloc((da)->items, (da)->capacity * sizeof(*(da)->items)); \
assert((da)->items != NULL && "Buy more RAM lol"); \
} \
} while (0)
// Append an item to a dynamic array
#define da_append(da, item) \
do { \
da_reserve((da), (da)->count + 1); \
(da)->items[(da)->count++] = (item); \
} while (0)
typedef struct {
const char **items;
size_t count;
size_t capacity;
} Cmd;
typedef struct {
size_t count;
const char *data;
} String_View;
String_View sv_chop_by_delim(String_View *sv, char delim)
{
size_t i = 0;
while (i < sv->count && sv->data[i] != delim) {
i += 1;
}
String_View result = {
.data = sv->data,
.count = i,
};
if (i < sv->count) {
sv->count -= i + 1;
sv->data += i + 1;
} else {
sv->count -= i;
sv->data += i;
}
return result;
}
#define BOARD_ROWS 10
#define BOARD_COLS 10
#define COL_WIDTH 3
#define BOARD_SIZE_IN_BYTES ((BOARD_COLS*COL_WIDTH)*BOARD_ROWS + BOARD_ROWS)
bool interactive = false;
bool is_board_char(char x)
{
const char *board_chars = " .[]@%\n";
return strchr(board_chars, x) || isdigit(x);
}
void parse_board(String_View sv, char *board, int *cur_row, int *cur_col)
{
for (size_t row = 0; sv.count > 0 && row < BOARD_ROWS; ++row) {
String_View line = sv_chop_by_delim(&sv, '\n');
assert(line.count == BOARD_COLS*COL_WIDTH);
for (size_t col = 0; col < BOARD_COLS; ++col) {
char l = line.data[col*COL_WIDTH + 0];
char c = line.data[col*COL_WIDTH + 1];
char r = line.data[col*COL_WIDTH + 2];
if (l == '[') {
assert(r == ']');
assert(*cur_row < 0);
assert(*cur_col < 0);
*cur_row = row;
*cur_col = col;
}
board[row*BOARD_COLS + col] = c;
}
}
assert(cur_row >= 0);
assert(cur_col >= 0);
}
void trace_board(char *board, size_t cur_row, size_t cur_col)
{
for (size_t row = 0; row < BOARD_ROWS; ++row) {
for (size_t col = 0; col < BOARD_COLS; ++col) {
bool cur = row == cur_row && col == cur_col;
printf("%c", cur ? '[' : ' ');
printf("%c", board[row*BOARD_COLS + col]);
printf("%c", cur ? ']' : ' ');
}
printf("\n");
}
if (interactive) {
usleep(10*1000);
}
}
bool something_is(char *board, char what)
{
for (size_t row = 0; row < BOARD_ROWS; ++row) {
for (size_t col = 0; col < BOARD_COLS; ++col) {
if (board[row*BOARD_COLS + col] == what) return true;
}
}
return false;
}
bool everything_is(char *board, char what)
{
for (size_t row = 0; row < BOARD_ROWS; ++row) {
for (size_t col = 0; col < BOARD_COLS; ++col) {
if (board[row*BOARD_COLS + col] != what) return false;
}
}
return true;
}
static inline bool everything_is_closed(char *board)
{
return everything_is(board, '.');
}
inline static bool something_is_closed(char *board)
{
return something_is(board, '.');
}
void write_char(int fd, char cmd)
{
ssize_t n = write(fd, &cmd, 1);
if (n == 0) exit(0);
if (n < 0) {
fprintf(stderr, "ERROR: could not write into input of the child: %s\n", strerror(errno));
abort();
}
}
char read_char(int fd)
{
char buf;
ssize_t n = read(fd, &buf, 1);
if (n == 0) exit(0);
if (n < 0) {
fprintf(stderr, "ERROR: could not read output of the child: %s\n", strerror(errno));
abort();
}
return buf;
}
typedef enum {
START,
BOARD,
TURN,
REFRESH,
WON,
LOST,
} Harness_State;
const char *harness_name(Harness_State state)
{
switch (state) {
case START: return "START";
case BOARD: return "BOARD";
case TURN: return "TURN";
case REFRESH: return "REFRESH";
case WON: return "WON";
case LOST: return "LOST";
default: UNREACHABLE("State");
}
}
typedef enum {
DECIDE,
WALKING,
} Agent_State;
typedef struct {
int row, col;
} Coord;
static inline Coord make_coord(int row, int col)
{
Coord coord;
coord.row = row;
coord.col = col;
return coord;
}
typedef struct {
Coord *items;
size_t count;
size_t capacity;
} Coords;
bool check_prompt(int fd, char buf, const char *prompt)
{
while (buf == *prompt) {
prompt += 1;
if (*prompt == 0) break;
buf = read_char(fd);
}
return *prompt == 0;
}
void count_nbors(char *board, Coord coord, char kind, Coords *nbors)
{
for (int dx = -1; dx <= 1; ++dx) {
int col = coord.col + dx;
if (!(0 <= col && col < BOARD_COLS)) continue;
for (int dy = -1; dy <= 1; ++dy) {
if (dx == 0 && dy == 0) continue;
int row = coord.row + dy;
if (!(0 <= row && row < BOARD_ROWS)) continue;
if (board[row*BOARD_COLS + col] == kind) {
da_append(nbors, make_coord(row, col));
}
}
}
}
void thinking(const char *fmt, ...) PRINTF_FORMAT(1, 2);
void thinking(const char *fmt, ...)
{
if (!interactive) {
printf("THINKING: ");
va_list args;
va_start(args, fmt);
vprintf(fmt, args);
va_end(args);
printf("\n");
}
}
typedef enum {
OPEN,
FLAG,
} Solver_Action;
#define da_random(da) (assert((da)->count > 0), (da)->items[rand()%(da)->count])
Solver_Action solver(char *board, Coord *coord)
{
if (everything_is_closed(board)) {
thinking("Everything is closed. This is the start of the game. Opening a random cell.");
coord->row = rand()%BOARD_ROWS;
coord->col = rand()%BOARD_COLS;
return OPEN;
}
assert(something_is_closed(board));
static Coords closed_nbors = {0};
static Coords flagged_nbors = {0};
for (int row = 0; row < BOARD_ROWS; ++row) {
for (int col = 0; col < BOARD_COLS; ++col) {
if (board[row*BOARD_COLS + col] == '@') {
UNREACHABLE("A bomb slipped into the solver at row %d column %d", row, col);
}
if (isdigit(board[row*BOARD_COLS + col])) {
closed_nbors.count = 0;
flagged_nbors.count = 0;
count_nbors(board, make_coord(row, col), '.', &closed_nbors);
count_nbors(board, make_coord(row, col), '%', &flagged_nbors);
size_t mine_count = board[row*BOARD_COLS + col] - '0';
if (flagged_nbors.count > mine_count) {
UNREACHABLE("Overflagged! (flagged: %zu, mines: %zu)", flagged_nbors.count, mine_count);
}
mine_count -= flagged_nbors.count;
if (mine_count == 0) {
if (closed_nbors.count > 0) {
*coord = da_random(&closed_nbors);
thinking("Found a good candidate to open at row %d, column %d", coord->row, coord->col);
return OPEN;
}
} else if (mine_count == closed_nbors.count) {
*coord = da_random(&closed_nbors);
thinking("Found a good candidate to FLAG at row %d, column %d", coord->row, coord->col);
return FLAG;
}
}
}
}
closed_nbors.count = 0;
for (int row = 0; row < BOARD_ROWS; ++row) {
for (int col = 0; col < BOARD_COLS; ++col) {
if (board[row*BOARD_COLS + col] == '.') {
da_append(&closed_nbors, make_coord(row, col));
}
}
}
*coord = da_random(&closed_nbors);
thinking("Could not find any obvious candidates. Picking a random cell at row %d, column %d", coord->row, coord->col);
return OPEN;
}
int main(int argc, char **argv)
{
const char *program_name = shift(argv, argc);
while (argc > 0) {
if (strcmp(argv[0], "-i") == 0) {
interactive = true;
shift(argv, argc);
} else {
break;
}
}
if (argc <= 0) {
fprintf(stderr, "Usage: %s [OPTIONS] [COMMAND LINE...]\n", program_name);
fprintf(stderr, "OPTIONS:\n");
fprintf(stderr, " -i\n");
fprintf(stderr, " Run the solver in interactive mode\n");
fprintf(stderr, "ERROR: no command line is provided\n");
return 1;
}
struct termios tattr, saved_tattr;
if (interactive) {
if (isatty(STDIN_FILENO)) {
tcgetattr(STDIN_FILENO, &tattr);
saved_tattr = tattr;
tattr.c_lflag &= (~(ICANON | ECHO));
tattr.c_cc[VMIN] = 1;
tattr.c_cc[VTIME] = 0;
tcsetattr(STDIN_FILENO, TCSAFLUSH, &tattr);
}
}
int input_pipe[2];
if (pipe(input_pipe) < 0) {
fprintf(stderr, "ERROR: could not create input pipe: %s\n", strerror(errno));
return 1;
}
int input_pipe_read = input_pipe[0];
int input_pipe_write = input_pipe[1];
int output_pipe[2];
if (pipe(output_pipe) < 0) {
fprintf(stderr, "ERROR: could not create output pipe: %s\n", strerror(errno));
return 1;
}
int output_pipe_read = output_pipe[0];
int output_pipe_write = output_pipe[1];
pid_t child = fork();
if (child == 0) {
if (dup2(input_pipe_read, STDIN_FILENO) < 0) {
fprintf(stderr, "ERROR: Could not setup stdin for child process: %s\n", strerror(errno));
exit(1);
}
close(input_pipe_write);
if (dup2(output_pipe_write, STDOUT_FILENO) < 0) {
fprintf(stderr, "ERROR: Could not setup stdout for child process: %s\n", strerror(errno));
exit(1);
}
close(output_pipe_read);
Cmd cmd = {0};
while (argc > 0) {
da_append(&cmd, shift(argv, argc));
}
da_append(&cmd, NULL);
if (execvp(*cmd.items, (char *const*)cmd.items) < 0) {
fprintf(stderr, "ERROR: could not start child process: %s\n", strerror(errno));
exit(1);
}
}
close(input_pipe_read);
close(output_pipe_write);
Harness_State harness = START;
Agent_State agent = DECIDE;
Coord agent_target;
Solver_Action solver_action;
String_Builder output = {0};
for (;;) { // Agentic loop
switch (harness) {
case START: {
char buf = read_char(output_pipe_read);
if (is_board_char(buf)) {
sb_append(&output, buf);
harness = BOARD;
} else {
UNREACHABLE("%s: does not look like a board", harness_name(harness));
}
} break;
case BOARD: {
if (output.count < BOARD_SIZE_IN_BYTES) {
char buf = read_char(output_pipe_read);
if (is_board_char(buf)) {
sb_append(&output, buf);
harness = BOARD;
} else {
UNREACHABLE("%s: does not look like a board: %c", harness_name(harness), buf);
}
} else if (output.count == BOARD_SIZE_IN_BYTES) {
harness = TURN;
} else {
assert(output.count > BOARD_SIZE_IN_BYTES);
UNREACHABLE("%s: board too big (%zu, expected %d)", harness_name(harness), output.count, BOARD_SIZE_IN_BYTES);
}
} break;
case TURN: {
int cur_row = -1;
int cur_col = -1;
char board[BOARD_COLS*BOARD_ROWS] = {0};
parse_board(sb_to_sv(output), board, &cur_row, &cur_col);
output.count = 0;
trace_board(board, cur_row, cur_col);
if (something_is(board, '@')) {
thinking("I see bombs. Looks like we died...");
harness = LOST;
} else if (something_is(board, '.')) {
switch (agent) {
case DECIDE:
solver_action = solver(board, &agent_target);
switch (solver_action) {
case OPEN: // fallthrough
case FLAG:
agent = WALKING;
break;
default: UNREACHABLE("Solver_Action");
}
// fallthrough
case WALKING:
if (cur_row < agent_target.row) {
thinking("moving down");
write_char(input_pipe_write, 's');
agent = WALKING;
} else if (cur_row > agent_target.row) {
thinking("moving up");
write_char(input_pipe_write, 'w');
agent = WALKING;
} else if (cur_col < agent_target.col) {
thinking("moving right");
write_char(input_pipe_write, 'd');
agent = WALKING;
} else if (cur_col > agent_target.col) {
thinking("moving left");
write_char(input_pipe_write, 'a');
agent = WALKING;
} else {
switch (solver_action) {
case OPEN:
thinking("opening");
write_char(input_pipe_write, ' ');
agent = DECIDE;
break;
case FLAG:
thinking("flagging");
write_char(input_pipe_write, 'f');
agent = DECIDE;
break;
default: UNREACHABLE("Solver_Action");
}
}
harness = REFRESH;
break;
default: UNREACHABLE("Action_State");
}
} else {
thinking("I see neither bombs nor closed cells. Looks like we won!");
harness = WON;
}
} break;
case REFRESH: {
const char *reset_escape_sequence = "\x1b[10A\x1b[30D";
char buf = read_char(output_pipe_read);
if (!check_prompt(output_pipe_read, buf, reset_escape_sequence)) {
UNREACHABLE("%s: weird reset sequence has been recieved", harness_name(harness));
}
if (interactive) {
printf("%s", reset_escape_sequence);
}
harness = BOARD;
} break;
case LOST: {
const char *you_died_restart = "You Died! Restart? [y/n] ";
char buf = read_char(output_pipe_read);
if (!check_prompt(output_pipe_read, buf, you_died_restart)) {
UNREACHABLE("%s: weird you_died_restart sequence has been recieved", harness_name(harness));
}
printf("%s", you_died_restart);
char default_choice = 'y';
write_char(input_pipe_write, default_choice);
if (read_char(output_pipe_read) != default_choice) {
UNREACHABLE("%s: weird you_died_restart response has been recieved", harness_name(harness));
}
if (read_char(output_pipe_read) != '\n') {
UNREACHABLE("%s: weird you_died_restart response has been recieved", harness_name(harness));
}
printf("%c\n", default_choice);
harness = BOARD;
} break;
case WON: {
const char *you_won_restart = "You Won! Restart? [y/n] ";
char buf = read_char(output_pipe_read);
if (!check_prompt(output_pipe_read, buf, you_won_restart)) {
UNREACHABLE("%s: weird you_won_restart sequence has been recieved", harness_name(harness));
}
printf("%s", you_won_restart);
char default_choice = 'n';
write_char(input_pipe_write, default_choice);
if (read_char(output_pipe_read) != default_choice) {
UNREACHABLE("%s: weird you_won_restart response has been recieved", harness_name(harness));
}
if (read_char(output_pipe_read) != '\n') {
UNREACHABLE("%s: weird you_won_restart response has been recieved", harness_name(harness));
}
printf("%c\n", default_choice);
goto over;
} break;
default: UNREACHABLE("harness");
}
} over:
if (interactive) {
if (isatty(STDIN_FILENO)) {
tcsetattr(STDIN_FILENO, TCSANOW, &saved_tattr);
}
}
return 0;
}
// TODO: maybe kill the child process and restore the terminal state somewhere in atexit
// Sometimes when the solver hits an abort() the child process just turns into zombie.