Merge branch 'master' of ssh://repo.or.cz/srv/git/pachi
[pachi/json.git] / test.c
blob4b66d89bc9651a4b27a0ab7c2000471e5d915f59
1 #define DEBUG
2 #include <ctype.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <string.h>
7 #include "board.h"
8 #include "debug.h"
9 #include "tactics.h"
10 #include "random.h"
12 int debug_level = 1;
13 static bool board_printed;
15 void
16 board_load(struct board *b, FILE *f, int size)
18 board_printed = false;
19 board_resize(b, size);
20 board_clear(b);
21 for (int y = size - 1; y >= 0; y--) {
22 char line[256];
23 if (!fgets(line, sizeof(line), f)) {
24 fprintf(stderr, "Premature EOF.\n");
25 exit(EXIT_FAILURE);
27 line[strlen(line) - 1] = 0; // chomp
28 if (strlen(line) != size) {
29 fprintf(stderr, "Line not %d char long: %s\n", size, line);
30 exit(EXIT_FAILURE);
32 for (int x = 0; x < size; x++) {
33 enum stone s;
34 switch (line[x]) {
35 case '.': s = S_NONE; break;
36 case 'X': s = S_BLACK; break;
37 case 'O': s = S_WHITE; break;
38 default: fprintf(stderr, "Invalid stone %c\n", line[x]);
39 exit(EXIT_FAILURE);
41 if (s == S_NONE) continue;
42 struct move m = { .color = s, .coord = coord_xy(b, x + 1, y + 1) };
43 if (board_play(b, &m) < 0) {
44 fprintf(stderr, "Failed to play %s %s\n",
45 stone2str(s), coord2sstr(m.coord, b));
46 board_print(b, stderr);
47 exit(EXIT_FAILURE);
51 if (DEBUGL(2))
52 board_print(b, stderr);
55 void
56 test_sar(struct board *b, char *arg)
58 enum stone color = str2stone(arg);
59 arg += 2;
60 coord_t *cc = str2coord(arg, board_size(b));
61 coord_t c = *cc; coord_done(cc);
62 arg += strcspn(arg, " ") + 1;
63 int eres = atoi(arg);
64 if (DEBUGL(1))
65 printf("sar %s %s %d...\t", stone2str(color), coord2sstr(c, b), eres);
67 int rres = is_bad_selfatari(b, color, c);
69 if (rres == eres) {
70 if (DEBUGL(1))
71 printf("OK\n");
72 } else {
73 if (debug_level <= 2) {
74 if (DEBUGL(0) && !board_printed) {
75 board_print(b, stderr);
76 board_printed = true;
78 printf("sar %s %s %d...\t", stone2str(color), coord2sstr(c, b), eres);
80 printf("FAILED (%d)\n", rres);
85 int main(int argc, char *argv[])
87 if (argc < 2) {
88 fprintf(stderr, "Usage: %s TESTFILE [DEBUGLEVEL]\n", argv[0]);
89 exit(EXIT_FAILURE);
92 if (argc > 2)
93 debug_level = atoi(argv[2]);
95 FILE *f = fopen(argv[1], "r");
96 if (!f) {
97 perror(argv[1]);
98 exit(EXIT_FAILURE);
101 struct board *b = board_init();
102 char line[256];
103 while (fgets(line, sizeof(line), f)) {
104 line[strlen(line) - 1] = 0; // chomp
105 switch (line[0]) {
106 case '%': printf("\n%s\n", line); continue;
107 case 0: continue;
109 if (!strncmp(line, "boardsize ", 10)) {
110 board_load(b, f, atoi(line + 10));
111 } else if (!strncmp(line, "sar ", 4)) {
112 test_sar(b, line + 4);
113 } else {
114 fprintf(stderr, "Syntax error: %s\n", line);
115 exit(EXIT_FAILURE);
119 fclose(f);
120 return 0;