blob: 7518a780111e197bd6457a9a18890a5e22fe81d1 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
|
#include <ctype.h>
#include <string.h>
#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;
}
/*
* 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;
}
|