src/chess/knight.c

changeset 47
d726e4b46c33
parent 23
824c9522ce66
child 55
54ea19938d57
equal deleted inserted replaced
46:4dcfb4c58b6d 47:d726e4b46c33
35 int dx = abs(move->fromfile - move->tofile); 35 int dx = abs(move->fromfile - move->tofile);
36 int dy = abs(move->fromrow - move->torow); 36 int dy = abs(move->fromrow - move->torow);
37 37
38 return (dx == 2 && dy == 1) || (dx == 1 && dy == 2); 38 return (dx == 2 && dy == 1) || (dx == 1 && dy == 2);
39 } 39 }
40
41 static int knight_getloc_fixedrow(GameState *gamestate, Move *move) {
42 int d = 3 - abs(move->fromrow - move->torow);
43
44 if (d == 1 || d == 2) {
45 if (move->tofile < 6 &&
46 gamestate->board[move->fromrow][move->tofile + d] == move->piece) {
47 if (move->fromfile == POS_UNSPECIFIED) {
48 move->fromfile = move->tofile + d;
49 return VALID_MOVE_SYNTAX;
50 } else {
51 return AMBIGUOUS_MOVE;
52 }
53 }
54 if (move->tofile > 1 &&
55 gamestate->board[move->fromrow][move->tofile - d] == move->piece) {
56 if (move->fromfile == POS_UNSPECIFIED) {
57 move->fromfile = move->tofile - d;
58 return VALID_MOVE_SYNTAX;
59 } else {
60 return AMBIGUOUS_MOVE;
61 }
62 }
63 }
64
65 return INVALID_POSITION;
66 }
67
68 static int knight_getloc_fixedfile(GameState *gamestate, Move *move) {
69 int d = 3 - abs(move->fromfile - move->tofile);
70
71 if (d == 1 || d == 2) {
72 if (move->torow < 6 &&
73 gamestate->board[move->torow + d][move->fromfile] == move->piece) {
74 if (move->fromrow == POS_UNSPECIFIED) {
75 move->fromrow = move->torow + d;
76 return VALID_MOVE_SYNTAX;
77 } else {
78 return AMBIGUOUS_MOVE;
79 }
80 }
81 if (move->torow > 1 &&
82 gamestate->board[move->torow - d][move->fromfile] == move->piece) {
83 if (move->fromrow == POS_UNSPECIFIED) {
84 move->fromrow = move->torow - d;
85 return VALID_MOVE_SYNTAX;
86 } else {
87 return AMBIGUOUS_MOVE;
88 }
89 }
90 }
91
92 return INVALID_POSITION;
93 }
94
95 int knight_getlocation(GameState *gamestate, Move *move) {
96
97 if (move->fromfile != POS_UNSPECIFIED) {
98 return knight_getloc_fixedfile(gamestate, move);
99 }
100
101 if (move->fromrow != POS_UNSPECIFIED) {
102 return knight_getloc_fixedrow(gamestate, move);
103 }
104
105 for (int x = -2 ; x <= 2 ; x++) {
106 if (x == 0) {
107 continue;
108 }
109 for (int y = -2 ; y <= 2 ; y++) {
110 if (y == 0 || y == x) {
111 continue;
112 }
113 uint8_t cx = move->tofile + x;
114 uint8_t cy = move->torow + y;
115
116 if (isidx(cx) && isidx(cy)
117 && gamestate->board[cy][cx] == move->piece) {
118 if (move->fromfile == POS_UNSPECIFIED
119 && move->fromrow == POS_UNSPECIFIED) {
120 move->fromfile = cx;
121 move->fromrow = cy;
122 } else {
123 return AMBIGUOUS_MOVE;
124 }
125 }
126 }
127 }
128
129 if (move->fromfile == POS_UNSPECIFIED || move->fromrow == POS_UNSPECIFIED) {
130 return INVALID_POSITION;
131 } else {
132 return VALID_MOVE_SYNTAX;
133 }
134 }

mercurial