git.haldean.org grandmaster / df274a8
add move-to-pgn converter Haldean 3 years ago
2 changed file(s) with 50 addition(s) and 0 deletion(s). Raw diff Collapse all Expand all
7575 void
7676 free_move_tree(struct move *move);
7777
78 /* Creates PGN for a given move. In most cases, callers should use
79 * move->post_board->pgn instead; this is what is used to populate the pgn field
80 * on the board struct. */
81 char *
82 create_pgn(struct move *move);
83
7884 #endif
1919 #include "grandmaster/core.h"
2020 #include "grandmaster/internal.h"
2121
22 #include <stdio.h>
2223 #include <stdlib.h>
2324 #include <string.h>
2425
154155 free_move_tree(last);
155156 return NULL;
156157 }
158
159 char *
160 create_pgn(struct move *move)
161 {
162 char *base;
163 char *res;
164 size_t base_len;
165 int ret;
166
167 /* if we're the root node, there's no need to include us in the PGN. */
168 if (move->algebraic == NULL)
169 return "";
170
171 if (move->parent != NULL) {
172 base = create_pgn(move->parent);
173 base_len = strlen(base);
174 } else {
175 base = "";
176 base_len = 0;
177 }
178
179 /* propagate errors back up the stack. */
180 if (base == NULL)
181 return NULL;
182
183 if (move->player == WHITE) {
184 if (base_len > 0)
185 ret = asprintf(&res, "%s %d.%s",
186 base,
187 move->post_board->ply_index / 2 + 1,
188 move->algebraic);
189 else
190 ret = asprintf(&res, "%d.%s",
191 move->post_board->ply_index / 2 + 1,
192 move->algebraic);
193 } else {
194 ret = asprintf(&res, "%s %s", base, move->algebraic);
195 }
196
197 if (ret == -1)
198 return NULL;
199 return res;
200 }