#include #include #include "coordinate.h" /* * Returns 0 if the coordinate is between a1 and h8. */ int coord_is_valid(char *s) { if (strnlen(s, 3) != 2) return 1; char col = tolower(s[0]); char row = tolower(s[1]); if (col >= 'a' && col <= 'h' && row >= '1' && row <= '8') return 0; return 2; } /* * Does not check if s is a valid string representing. If input is * untrusted, use coord_is_valid(char*) to check it. */ Coord coord_init(char* s) { Coord c; char col = tolower(s[0]); char row = tolower(s[1]); c.col = col; c.row = row; return c; } /* * Returns 0 if c is the null coordinate */ int coord_is_null(Coord c) { return (c.col == 0 && c.row == 0); } /* * Returns the null coordinate */ Coord coord_null() { Coord c; c.col = 0; c.row = 0; return c; } /* * Set Coord row */ Coord coord_set_row(Coord c, char row) { c.row = row; return c; } /* * Set Coord column */ Coord coord_set_col(Coord c, char col) { c.col = col; return c; } /* * Get Coord row */ char coord_get_row(Coord c) { return c.row; } /* * Get Coord column */ char coord_get_col(Coord c) { return c.col; } /* * Returns the next coordinate. Useful for traversing the board forwards. */ Coord coord_next(Coord c) { if (coord_is_null(c)) c = coord_init("a8"); else if (c.col == 'h') if (c.row == '1') c = coord_null(); else { c.row -= 1; c.col = 'a'; } else c.col += 1; return c; } /* * Returns the previous coordinate. Useful for traversing the board backwards. */ Coord coord_prev(Coord c) { if (coord_is_null(c)) c = coord_init("h1"); else if (c.col == 'a') if (c.row == '8') c = coord_null(); else { c.row += 1; c.col = 'h'; } else c.col -= 1; return c; }