From 922eef24c4ee4116c51eaf175b55f71e94fce6c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ra=C3=BAl=20Benencia?= Date: Sat, 28 Mar 2015 17:04:01 -0300 Subject: use coordinates --- lib/coordinate.c | 109 ++++++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 95 insertions(+), 14 deletions(-) (limited to 'lib/coordinate.c') diff --git a/lib/coordinate.c b/lib/coordinate.c index 2dc0215..7518a78 100644 --- a/lib/coordinate.c +++ b/lib/coordinate.c @@ -3,29 +3,110 @@ #include "coordinate.h" -static int _valid_coord(char col, char row) { +/* + * 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 1; + return 2; } -int coord_init(Coord* c, char col, char row) { - char lower_col = tolower(col); - char lower_row = tolower(row); +/* + * 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]); - if (! _valid_coord(lower_col, lower_row)) - return 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); +} - c->row = row; - c->col = col; +/* + * Returns the null coordinate + */ +Coord coord_null() { + Coord c; - return 0; + c.col = 0; + c.row = 0; + + return c; } -int coord_init_from_str(Coord* c, char* s) { - if (strlen(s) != 2) - return 1; +/* + * 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; +} + +/* + * 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 coord_init(c, s[0], s[1]); + return c; } -- cgit v1.2.3