summaryrefslogtreecommitdiff
path: root/lib/coordinate.c
diff options
context:
space:
mode:
authorRaúl Benencia <rul@kalgan.cc>2015-03-28 17:04:01 -0300
committerRaúl Benencia <rul@kalgan.cc>2015-03-28 17:04:01 -0300
commit922eef24c4ee4116c51eaf175b55f71e94fce6c4 (patch)
tree68072d9e30b42952dc66692adf16fb45c52fb96e /lib/coordinate.c
parenta7f2a09bce2d94c236469843d0815803edbf3574 (diff)
use coordinates
Diffstat (limited to 'lib/coordinate.c')
-rw-r--r--lib/coordinate.c109
1 files changed, 95 insertions, 14 deletions
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;
}
nihil fit ex nihilo