chess-turn-engine 0.1.1

Chess turn engine library with all chess rules implemented. Can be used to implement a chess game.
Documentation
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
use super::board_map::BoardMap;
use super::game_error::GameError;
use super::side::Side;
use chess_notation_parser::{Piece, Square};

const DIR_N: Coordinate = Coordinate { x: 0, y: 1 };
const DIR_S: Coordinate = Coordinate { x: 0, y: -1 };
const DIR_E: Coordinate = Coordinate { x: 1, y: 0 };
const DIR_W: Coordinate = Coordinate { x: -1, y: 0 };

const DIR_NE: Coordinate = Coordinate { x: 1, y: 1 };
const DIR_NW: Coordinate = Coordinate { x: -1, y: 1 };
const DIR_SE: Coordinate = Coordinate { x: -1, y: -1 };
const DIR_SW: Coordinate = Coordinate { x: 1, y: -1 };

/// Pawn direction
enum PawnDir {
    Forward,
    Backward,
}

/// Piece movement
///
/// Purpose of this struct is to have clear pawn moving patterns depending on
/// their `capture` condition
#[derive(Clone, Copy)]
pub enum PieceMove {
    King,
    Queen,
    Bishop,
    Knight,
    Rook,

    /// Pawn moving diagonally
    PawnCapture,

    /// Pawn moving forward
    PawnNormal,
}

impl PieceMove {
    /// Convert to piece
    pub fn to_piece(&self) -> Piece {
        match self {
            PieceMove::Queen => Piece::Queen,
            PieceMove::King => Piece::King,
            PieceMove::Bishop => Piece::Bishop,
            PieceMove::Knight => Piece::Knight,
            PieceMove::Rook => Piece::Rook,
            _ => Piece::Pawn,
        }
    }
}

impl From<Piece> for PieceMove {
    fn from(piece: Piece) -> Self {
        match piece {
            Piece::Queen => PieceMove::Queen,
            Piece::King => PieceMove::King,
            Piece::Bishop => PieceMove::Bishop,
            Piece::Knight => PieceMove::Knight,
            Piece::Rook => PieceMove::Rook,
            _ => panic!("Not implemented for pawns"),
        }
    }
}

/// Chessboard coordinates
#[derive(Clone, Copy)]
struct Coordinate {
    /// 'file' axis
    x: i8,

    /// 'rank' axis
    y: i8,
}

/// Description of movement pattern
///
/// Iterator which can be used to get all possible squares for a certain pattern
/// using the current position, direction and 'squares left' info.
struct MovePattern {
    /// Current position
    dst: Square,

    /// Steps left for the direction
    moves_left: u8,

    /// Direction
    dir: Coordinate,
}

impl Iterator for MovePattern {
    type Item = Square;

    fn next(&mut self) -> Option<Self::Item> {
        if self.moves_left == 0 {
            return None;
        }

        let dst = match self.dst.get_relative_neighbor(self.dir.x, self.dir.y) {
            Err(_) => {
                self.moves_left = 0;
                return None;
            }
            Ok(square) => square,
        };

        self.moves_left -= 1;
        self.dst = dst;
        Some(dst)
    }
}

/// Get pattern for a given piece
///
/// Argument `side` is relevant only for pawns
fn get_move_pattern(
    square: Square,
    side: Side,
    piece_move: PieceMove,
    dir: PawnDir,
) -> Vec<MovePattern> {
    match piece_move {
        PieceMove::PawnNormal => get_moves_pawn_normal(square, side, dir),
        PieceMove::PawnCapture => get_moves_pawn_capture(square, side, dir),
        PieceMove::Queen => get_moves_queen(square),
        PieceMove::Bishop => get_moves_bishop(square),
        PieceMove::Rook => get_moves_rook(square),
        PieceMove::Knight => get_moves_knight(square),
        PieceMove::King => get_moves_king(square),
    }
}

/// Looking at the destination square, find all possible squares that
/// contain the moving piece which can actually move to the given destination
///
/// # Arguments
///
/// * `map` - board map
/// * `dst` - Destination square for the moving piece
/// * `side` - Color of the moving piece
/// * `piece_move` - Moving piece which is moving encapsulated in `PieceMove`
pub fn possible_squares_for_dst(
    map: &BoardMap,
    dst: Square,
    side: Side,
    piece_move: PieceMove,
) -> Vec<Square> {
    let dep_moves = get_move_pattern(dst, side, piece_move, PawnDir::Backward);
    let mut src_squares: Vec<Square> = vec![];

    // Filter out all possible source squares based on what we have on those
    // squares. We should find at least one piece of who we are looking for on
    // those squares.
    for mut dep_move in dep_moves {
        while let Some(square) = dep_move.next() {
            if let Some((p, s)) = map.get(&square) {
                if s == side && p == piece_move.to_piece() {
                    src_squares.push(square);
                }

                // We encontered anothere piece and we cannot jump over it.
                // Therefeore skip the direction, since it's blocking our path
                break;
            }
        }
    }

    src_squares
}

/// Get list of squares to which piece can move
///
/// # Arguments
///
/// * `map` - board map
/// * `src` - Source square for the moving piece
/// * `side` - Color of the moving piece
/// * `piece_move` - Moving piece which is moving encapsulated in `PieceMove`
pub fn possible_squares_for_src(
    map: &BoardMap,
    src: Square,
    side: Side,
    piece_move: PieceMove,
) -> Vec<Square> {
    let dep_moves = get_move_pattern(src, side, piece_move, PawnDir::Forward);
    let mut dst_squares: Vec<Square> = vec![];

    // Filter out all possible destination squares based on what we have on
    // those squares.
    for mut dep_move in dep_moves {
        while let Some(square) = dep_move.next() {
            if let Some((p, s)) = map.get(&square) {
                if s != side && p != Piece::King {
                    dst_squares.push(square);
                }

                // We encontered anothere piece and we cannot jump over it.
                // Therefeore skip the direction, since it's blocking our path
                break;
            }

            // We can move on empty squares
            dst_squares.push(square)
        }
    }

    dst_squares
}

/// Find exact source square by comparing possible squares with info about
/// the source squares that was received from the annotated turn
///
/// # Arguments
///
/// * `possible_src` - list of all possible source squares based on the current
///     board state.
/// * `turn_src` - Info about originating source square provided via turn
///     notation. e.g. dxe5 -> 'd' here represents the whole 'd' rank
pub fn get_exact_src(
    mut possible_src: Vec<Square>,
    turn_src: Option<Vec<Square>>,
) -> Result<Square, GameError> {
    let err = Err(GameError::MovingPieceNotFound);
    let mut exact_src_square = None;

    let turn_src: Vec<Square> = match turn_src {
        None if possible_src.len() != 1 => return err,
        None => return Ok(possible_src.pop().unwrap()),
        Some(src_squares) => src_squares,
    };

    for square in possible_src.into_iter() {
        if turn_src.contains(&square) {
            if exact_src_square.is_some() {
                return err;
            }
            exact_src_square = Some(square);
        }
    }

    match exact_src_square.is_none() {
        true => err,
        _ => Ok(exact_src_square.unwrap()),
    }
}

#[rustfmt::skip]
fn get_moves_pawn_normal(
    dst: Square,
    side: Side,
    dir: PawnDir
) -> Vec<MovePattern> {
    let mut moves_left = 1;

    match side {
        Side::White => {
            let (dir, rank) = match dir {
                PawnDir::Backward => (DIR_S, '4'),
                _ => (DIR_N, '2')
            };

            if Square::get_rank(rank).unwrap().contains(&dst) {
                moves_left = 2;
            };

            vec![MovePattern { dst, moves_left, dir }]
        },
        Side::Black => {
            let (dir, rank) = match dir {
                PawnDir::Backward => (DIR_N, '5'),
                _ => (DIR_S, '7')
            };

            if Square::get_rank(rank).unwrap().contains(&dst) {
                moves_left = 2;
            };

            vec![MovePattern { dst, moves_left, dir }]
        }
    }
}

#[rustfmt::skip]
fn get_moves_pawn_capture(
    dst: Square,
    side: Side,
    dir: PawnDir
) -> Vec<MovePattern> {
    match side {
        Side::White => {
            match dir {
                PawnDir::Backward => vec![
                    MovePattern { dst, moves_left: 1, dir: DIR_SE, },
                    MovePattern { dst, moves_left: 1, dir: DIR_SW, },
                ],
                _ => vec![
                    MovePattern { dst, moves_left: 1, dir: DIR_NE, },
                    MovePattern { dst, moves_left: 1, dir: DIR_NW, },
                ]
            }
        },
        Side::Black => {
            match dir {
                PawnDir::Backward => vec![
                    MovePattern { dst, moves_left: 1, dir: DIR_NE, },
                    MovePattern { dst, moves_left: 1, dir: DIR_NW, },
                ],
                _ => vec![
                    MovePattern { dst, moves_left: 1, dir: DIR_SE, },
                    MovePattern { dst, moves_left: 1, dir: DIR_SW, },
                ]
            }
        }
    }
}

#[rustfmt::skip]
fn get_moves_queen(dst: Square) -> Vec<MovePattern> {
    #[allow(non_upper_case_globals)]
    const moves_left: u8 = 8;

    vec![
        MovePattern { dst, moves_left, dir: DIR_N, },
        MovePattern { dst, moves_left, dir: DIR_NE, },
        MovePattern { dst, moves_left, dir: DIR_E, },
        MovePattern { dst, moves_left, dir: DIR_SE, },
        MovePattern { dst, moves_left, dir: DIR_S, },
        MovePattern { dst, moves_left, dir: DIR_SW, },
        MovePattern { dst, moves_left, dir: DIR_W, },
        MovePattern { dst, moves_left, dir: DIR_NW, },
    ]
}

#[rustfmt::skip]
fn get_moves_bishop(dst: Square) -> Vec<MovePattern> {
    #[allow(non_upper_case_globals)]
    const moves_left: u8 = 8;

    vec![
        MovePattern { dst, moves_left, dir: DIR_NE, },
        MovePattern { dst, moves_left, dir: DIR_SE, },
        MovePattern { dst, moves_left, dir: DIR_SW, },
        MovePattern { dst, moves_left, dir: DIR_NW, },
    ]
}

#[rustfmt::skip]
fn get_moves_rook(dst: Square) -> Vec<MovePattern> {
    #[allow(non_upper_case_globals)]
    const moves_left: u8 = 8;

    vec![
        MovePattern { dst, moves_left, dir: DIR_N, },
        MovePattern { dst, moves_left, dir: DIR_E, },
        MovePattern { dst, moves_left, dir: DIR_S, },
        MovePattern { dst, moves_left, dir: DIR_W, },
    ]
}

#[rustfmt::skip]
fn get_moves_king(dst: Square) -> Vec<MovePattern> {
    #[allow(non_upper_case_globals)]
    const moves_left: u8 = 1;

    vec![
        MovePattern { dst, moves_left, dir: DIR_N, },
        MovePattern { dst, moves_left, dir: DIR_NE, },
        MovePattern { dst, moves_left, dir: DIR_E, },
        MovePattern { dst, moves_left, dir: DIR_SE, },
        MovePattern { dst, moves_left, dir: DIR_S, },
        MovePattern { dst, moves_left, dir: DIR_SW, },
        MovePattern { dst, moves_left, dir: DIR_W, },
        MovePattern { dst, moves_left, dir: DIR_NW, },
   ]
}

#[rustfmt::skip]
fn get_moves_knight(dst: Square) -> Vec<MovePattern> {
    #[allow(non_upper_case_globals)]
    const moves_left: u8 = 1;

    vec![
        MovePattern { dst, moves_left, dir: Coordinate { x: 1, y: 2 } },
        MovePattern { dst, moves_left, dir: Coordinate { x: 1, y: -2 } },
        MovePattern { dst, moves_left, dir: Coordinate { x: -1, y: 2 } },
        MovePattern { dst, moves_left, dir: Coordinate { x: -1, y: -2 } },
        MovePattern { dst, moves_left, dir: Coordinate { x: 2, y: 1 } },
        MovePattern { dst, moves_left, dir: Coordinate { x: 2, y: -1 } },
        MovePattern { dst, moves_left, dir: Coordinate { x: -2, y: 1 } },
        MovePattern { dst, moves_left, dir: Coordinate { x: -2, y: -1 } },
    ]
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    #[should_panic]
    fn piece_move_from_piece_to_piece() {
        assert_eq!(PieceMove::from(Piece::Queen).to_piece(), Piece::Queen);
        assert_eq!(PieceMove::from(Piece::Knight).to_piece(), Piece::Knight);
        assert_eq!(PieceMove::from(Piece::King).to_piece(), Piece::King);
        assert_eq!(PieceMove::from(Piece::Bishop).to_piece(), Piece::Bishop);
        assert_eq!(PieceMove::from(Piece::Rook).to_piece(), Piece::Rook);

        let pawn = PieceMove::PawnCapture;
        assert_eq!(pawn.to_piece(), Piece::Pawn);

        // Let's panic here
        let _pawn_move = PieceMove::from(Piece::Pawn);
    }
}