hexchess 2.2.0-alpha.1

A library for Gliński's hexagonal chess, and the brain of hexchess.club
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
use crate::h;
use crate::hexchess::pieces::king::king_moves_unsafe;
use crate::hexchess::pieces::knight::knight_moves_unsafe;
use crate::hexchess::pieces::pawn::pawn_moves_unsafe;
use crate::hexchess::pieces::straight_line::straight_line_moves_unsafe;
use crate::hexchess::san::San;
use serde_with::serde_as;
use serde::{Deserialize, Serialize};
use std::hash::Hash;

use crate::constants::{
    Color,
    HEXBOARD_GRAPH,
    INITIAL_POSITION,
    KNIGHT_GRAPH,
    Piece,
    PromotionPiece,
};

use crate::hexchess::utils::{
    get_color,
    is_legal_en_passant,
    step,
    index,
    position,
    walk_until_piece,
};

/// Hexchess game state
#[serde_as]
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub struct Hexchess {
    #[serde_as(as = "[_; 91]")]
    pub board: [Option<Piece>; 91],

    pub ep: Option<u8>,

    pub fullmove: u16,

    pub halfmove: u8,

    pub turn: Color,
}

impl Hexchess {
    /// apply a whitespace separated sequence of moves
    pub fn apply(&mut self, sequence: &str) -> Result<Self, String> {
        let mut clone = self.clone();
        let mut i: u32 = 0;

        for part in sequence.split_whitespace() {
            let san = match San::from(&part.to_string()) {
                Ok(san) => san,
                Err(_) => {
                    return Err(format!("invalid san at index {}: {}", i, part));
                },
            };

            if clone.apply_move(&san).is_err() {
                return Err(format!("illegal move at index {}: {}", i, part));
            }

            i += 1;
        }

        self.board = clone.board;
        self.turn = clone.turn;
        self.ep = clone.ep;
        self.fullmove = clone.fullmove;
        self.halfmove = clone.halfmove;

        Ok(*self)
    }

    /// apply legal move
    pub fn apply_move(&mut self, san: &San) -> Result<&Self, String> {
        if !self.is_legal(san) {
            return Err(format!("illegal move: {:?}", san));
        }

        self.apply_move_unsafe(san)
    }

    /// apply move, regardless of turn or legality
    pub fn apply_move_unsafe(&mut self, san: &San) -> Result<&Self, String> {
        let piece = match self.board[san.from as usize] {
            Some(piece) => piece,
            None => return Err(format!("cannot apply move from empty position: {}", san.from)),
        };

        // update halfmove
        if self.board[san.to as usize].is_some() || (
            piece == Piece::BlackPawn ||
            piece == Piece::WhitePawn
        ) {
            self.halfmove = 0;
        } else {
            self.halfmove += 1;
        }

        let color = get_color(&piece);

        // update fullmove and turn color
        if color == Color::Black {
            self.fullmove += 1;
            self.turn = Color::White;
        } else {
            self.turn = Color::Black;
        }

        // set from positions
        self.board[san.from as usize] = None;

        // set to position
        self.board[san.to as usize] = Some(
            match san.promotion {
                None => piece,
                Some(piece) => match color {
                    Color::Black => match piece {
                        PromotionPiece::Bishop => Piece::BlackBishop,
                        PromotionPiece::Knight => Piece::BlackKnight,
                        PromotionPiece::Queen => Piece::BlackQueen,
                        PromotionPiece::Rook => Piece::BlackRook,
                    },
                    Color::White => match piece {
                        PromotionPiece::Bishop => Piece::WhiteBishop,
                        PromotionPiece::Knight => Piece::WhiteKnight,
                        PromotionPiece::Queen => Piece::WhiteQueen,
                        PromotionPiece::Rook => Piece::WhiteRook,
                    },
                },
            }
        );

        // clear captured en passant
        if Some(san.to) == self.ep {
            let captured = match piece {
                Piece::BlackPawn => step(san.to, 0),
                Piece::WhitePawn => step(san.to, 6),
                _ => None,
            };

            match captured {
                Some(position) => self.board[position as usize] = None,
                None => {},
            };
        }

        // set en passsant
        self.ep = match piece {
            Piece::BlackPawn => match (san.from, san.to) {
                (h!("c7"), h!("c5")) => Some(h!("c6")),
                (h!("d7"), h!("d5")) => Some(h!("d6")),
                (h!("e7"), h!("e5")) => Some(h!("e6")),
                (h!("f7"), h!("f5")) => Some(h!("f6")),
                (h!("g7"), h!("g5")) => Some(h!("g6")),
                (h!("h7"), h!("h5")) => Some(h!("h6")),
                (h!("i7"), h!("i5")) => Some(h!("i6")),
                (h!("k7"), h!("k5")) => Some(h!("k6")),
                _ => None,
            },
            Piece::WhitePawn => match (san.from, san.to) {
                (h!("c2"), h!("c4")) => Some(h!("c3")),
                (h!("d3"), h!("d5")) => Some(h!("d4")),
                (h!("e4"), h!("e6")) => Some(h!("e5")),
                (h!("f5"), h!("f7")) => Some(h!("f6")),
                (h!("g4"), h!("g6")) => Some(h!("g5")),
                (h!("h3"), h!("h5")) => Some(h!("h4")),
                (h!("i2"), h!("i4")) => Some(h!("i3")),
                (h!("k1"), h!("k3")) => Some(h!("k2")),
                _ => None,
            },
            _ => None,
        };

        Ok(self)
    }

    /// get legal moves for current turn
    pub fn current_moves(&self) -> Vec<San> {
        let mut result: Vec<San> = vec![];

        for n in self.get_color(self.turn) {
            result.extend(self.moves_from(n));
        }

        result
    }

    /// get piece at position
    pub fn get(&self, position: &str) -> Option<Piece> {
        match index(position) {
            Ok(index) => self.board[index as usize],
            Err(_) => None,
        }
    }

    /// get positions occupied by a color
    pub fn get_color(&self, color: Color) -> Vec<u8> {
        let mut result: Vec<u8> = vec![];

        for (index, piece) in self.board.iter().enumerate() {
            match piece {
                Some(piece) => match get_color(piece) == color {
                    true => result.push(index as u8),
                    false => continue,
                },
                None => continue,
            };
        }

        result
    }

    /// get legal moves a position
    pub fn moves_from(&self, from: u8) -> Vec<San> {
        let piece = match self.board[from as usize] {
            Some(piece) => piece,
            None => return vec![],
        };

        let color = get_color(&piece);

        self.moves_from_unsafe(from)
            .into_iter()
            .filter(|san| {
                // clone the board and apply an unsafe move
                let mut clone = self.clone();
                
                let _ = clone.apply_move_unsafe(san);

                let king_position = match clone.find_king(color) {
                    Some(king) => king,
                    None => return true,
                };

                // filter self-check moves
                if
                    is_king_threat(&clone, &color, king_position) ||
                    is_knight_threat(&clone, &color, king_position) ||
                    is_pawn_threat(&clone, &color, king_position) ||
                    is_straight_line_threat(&clone, &color, king_position)
                {
                    return false;
                }

                true
            })
            .collect()
    }

    /// get moves from a position, regardless of turn or legality
    pub fn moves_from_unsafe(&self, from: u8) -> Vec<San> {
        let mut result: Vec<San> = vec![];

        let piece = match self.board[from as usize] {
            Some(piece) => piece,
            None => return result,
        };
        
        let color = get_color(&piece);

        result.extend(match piece {
            Piece::BlackKing | Piece::WhiteKing => {
                king_moves_unsafe(&self, from, &color)
            },
            Piece::BlackKnight | Piece::WhiteKnight => {
                knight_moves_unsafe(&self, from, &color)
            },
            Piece::BlackPawn | Piece::WhitePawn => {
                pawn_moves_unsafe(&self, from, &color)
            },
            Piece::BlackBishop | Piece::WhiteBishop => {
                straight_line_moves_unsafe(&self, &from, &color, &[1, 3, 5, 7, 9, 11])
            },
            Piece::BlackRook | Piece::WhiteRook => {
                straight_line_moves_unsafe(&self, &from, &color, &[0, 2, 4, 6, 8, 10])
            },
            Piece::BlackQueen | Piece::WhiteQueen => {
                straight_line_moves_unsafe(&self, &from, &color, &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
            }
        });
        
        result
    }

    /// create a new hexchess instance
    pub fn new() -> Self {
        Self {
            board: [None; 91],
            ep: None,
            fullmove: 1,
            halfmove: 0,
            turn: Color::White,
        }
    }

    /// find king by color
    pub fn find_king(&self, color: Color) -> Option<u8> {
        let king = match color {
            Color::Black => Piece::BlackKing,
            Color::White => Piece::WhiteKing,
        };

        for (index, piece) in self.board.iter().enumerate() {
            if piece == &Some(king) {
                return Some(index as u8);
            }
        }

        None
    }

    /// initialize a hexchess instance to the starting position
    pub fn init() -> Self {
        Self::parse(INITIAL_POSITION).unwrap()
    }

    /// test if the board is in check
    pub fn is_check(&self) -> bool {
        let king = match self.find_king(self.turn) {
            Some(king) => king,
            None => return false
        };

        let opposite_turn = match self.turn {
            Color::Black => Color::White,
            Color::White => Color::Black,
        };

        for n in self.get_color(opposite_turn) {
            for san in self.moves_from_unsafe(n) {
                if san.to == king {
                    return true
                }
            }
        }
        
        false
    }

    /// test if the board is in checkmate
    pub fn is_checkmate(&self) -> bool {
        self.is_check() && self.current_moves().len() == 0
    }

    /// test if move is legal
    pub fn is_legal(&self, san: &San) -> bool {
        let piece = match self.board[san.from as usize] {
            Some(piece) => piece,
            None => return false,
        };
        
        if get_color(&piece) != self.turn {
            return false;
        }

        self.moves_from(san.from)
            .iter()
            .any(|move_san| move_san == san)
    }

    /// test if the board is in stalemate
    pub fn is_stalemate(&self) -> bool {
        !self.is_check() && self.current_moves().len() == 0
    }

    /// test if position is threatened
    pub fn is_threatened(&self, position: u8) -> bool {
        let threatened_piece = match self.board[position as usize] {
            Some(piece) => piece,
            None => return false,
        };

        let color = get_color(&threatened_piece);

        for n in 0u8..91u8 {
            match self.board[n as usize] {
                Some(piece) => match color == get_color(&piece) {
                    true => continue,
                    false => {
                        for san in self.moves_from_unsafe(n) {
                            if san.to == position {
                                return true
                            }
                        }
                    }
                },
                None => continue,
            };
        }

        false
    }

    /// create hexchess instance from fen
    pub fn parse(source: &str) -> Result<Self, String> {
        let mut parts = source.split_whitespace();

        let board = match parts.next() {
            Some(part) => match parse_board(&part.to_string()) {
                Ok(result) => result,
                Err(failure) => return Err(failure),
            }
            _ => return Err("board not found".to_string()),
        };

        let turn = match parts.next() {
            Some(part) => match part {
                "b" => Color::Black,
                "w" => Color::White,
                _ => return Err(format!("invalid turn color: {}", part)),
            },
            None => Color::White,
        };

        let ep = match parts.next() {
            Some(part) => match part {
                "-" => None,
                _ => match index(&part) {
                    Ok(result) => match is_legal_en_passant(&result) {
                        true => Some(result),
                        false => return Err(format!("illegal en passant position: {}", part)),
                    },
                    Err(_) => return Err(format!("invalid en passant position: {}", part)),
                },
            },
            None => None,
        };

        let halfmove = match parts.next() {
            Some(part) => match part.parse::<u8>() {
              Ok(result) => result,
              Err(_) => return Err(format!("invalid halfmove: {}", part)),
            },
            None => 0,
        };

        let fullmove = match parts.next() {
            Some(part) => match part.parse::<u16>() {
                Ok(result) => match result >= 1 {
                    true => result,
                    false => return Err(format!("invalid fullmove: {}", part)),
                },
                Err(_) => return Err(format!("invalid fullmove: {}", part)),
            },
            None => 1,
        };

        Ok(Self {
            board,
            ep,
            fullmove,
            halfmove,
            turn,
        })
    }

    /// format as fen string
    pub fn to_string(&self) -> String {
        format!(
            "{} {} {} {} {}",
            stringify_board(&self.board),
            match self.turn {
                Color::Black => 'b',
                Color::White => 'w',
            },
            match self.ep {
                Some(ep) => position(&ep),
                None => "-",
            },
            self.halfmove,
            self.fullmove,
        )
    }
}

/// test if knight threatens a position
fn is_knight_threat(hexchess: &Hexchess, color: &Color, position: u8) -> bool {
    let hostile_knight = match color {
        Color::Black => Piece::WhiteKnight,
        Color::White => Piece::BlackKnight,
    };
    
    for n in KNIGHT_GRAPH[position as usize].iter() {
        if hexchess.board[*n as usize] == Some(hostile_knight) {
            return true
        }
    }

    false
}

/// test if position touches the hostile king
fn is_king_threat(hexchess: &Hexchess, color: &Color, position: u8) -> bool {
    let hostile_king = match color {
        Color::Black => Piece::WhiteKing,
        Color::White => Piece::BlackKing,
    };

    for n in HEXBOARD_GRAPH[position as usize] {
        if n.is_some() && hexchess.board[n.unwrap() as usize] == Some(hostile_king) {
            return true
        }
    }

    false
}

/// test if pawn threatens a position
fn is_pawn_threat(hexchess: &Hexchess, color: &Color, position: u8) -> bool {
    // portside and starboard are reversed from the pawn's perspective because
    // we only know the king's position. so we must move the king like friendly
    // pawn to see if it encounters a hostile pawn
    let (
        hostile_pawn,
        reverse_portside,
        reverse_starboard,
    ) = match color {
        Color::Black => (Piece::WhitePawn, 4, 8),
        Color::White => (Piece::BlackPawn, 10, 2),
    };

    match step(position, reverse_portside) {
        Some(index) => if hexchess.board[index as usize] == Some(hostile_pawn) {
            return true
        },
        None => {},
    }

    match step(position, reverse_starboard) {
        Some(index) => if hexchess.board[index as usize] == Some(hostile_pawn) {
            return true
        },
        None => {},
    }

    false
}

/// test if straight line piece threatens a position
fn is_straight_line_threat(hexchess: &Hexchess, color: &Color, position: u8) -> bool {
    let hostile_bishop = match color {
        Color::Black => Piece::WhiteBishop,
        Color::White => Piece::BlackBishop,
    };

    let hostile_queen = match color {
        Color::Black => Piece::WhiteQueen,
        Color::White => Piece::BlackQueen,
    };

    let hostile_rook = match color {
        Color::Black => Piece::WhiteRook,
        Color::White => Piece::BlackRook,
    };

    // check for diagonal threats
    for diagonal_direction in &[1u8, 3, 5, 7, 9, 11] {
        let piece = walk_until_piece(hexchess, position, *diagonal_direction);

        if piece == Some(hostile_bishop) || piece == Some(hostile_queen) {
            return true;
        }
    }

    // check for orthogonal threats
    for orthogonal_direction in &[0u8, 2, 4, 6, 8, 10] {
        let piece = walk_until_piece(hexchess, position, *orthogonal_direction);

        if piece == Some(hostile_rook) || piece == Some(hostile_queen) {
            return true;
        }
    }

    false
}

/// parse the board segment of fen
fn parse_board(source: &String) -> Result<[Option<Piece>; 91], String> {
    let mut arr: [Option<Piece>; 91] = [None; 91];
    let mut black = false;
    let mut white = false;
    let mut fen_index: u8 = 0;

    for (index, current) in source.chars().enumerate() {
        match current {
            '/' => continue,
            '0' => continue,
            '1' => match source.chars().nth(index as usize + 1) {
                Some('0') | Some('1') => fen_index += 10,
                _ => fen_index += 1,
            },
            '2' => fen_index += 2,
            '3' => fen_index += 3,
            '4' => fen_index += 4,
            '5' => fen_index += 5,
            '6' => fen_index += 6,
            '7' => fen_index += 7,
            '8' => fen_index += 8,
            '9' => fen_index += 9,
            'b' | 'B' | 'n' | 'N' | 'p' | 'P' | 'Q' | 'q' | 'r' | 'R' => {
                // // it's safe to unwrap current because our match already checks for it
                arr[fen_index as usize] = Some(to_piece(current).unwrap());

                fen_index += 1;
            }
            'k' => {
                if black {
                    return Err("multiple black kings".to_string());
                }

                arr[fen_index as usize] = Some(Piece::BlackKing);
                black = true;
                fen_index += 1;
            }
            'K' => {
                if white {
                    return Err("multiple white kings".to_string());
                }

                arr[fen_index as usize] = Some(Piece::WhiteKing);
                white = true;
                fen_index += 1;
            },
            _ => return Err(format!("invalid character at index {}: {}", index, current)),
        }
    }

    if fen_index != 91 {
        return Err("board overflow".to_string());
    }

    Ok(arr)
}

/// format the board section of a fen
fn stringify_board(board: &[Option<Piece>; 91]) -> String {
    let mut blank: u8 = 0;
    let mut index: u8 = 0;
    let mut result = String::new();

    for val in board.iter() {
        match val {
            None => {
                blank += 1;
            },
            Some(piece) => {
                if blank > 0 {
                    result.push_str(&blank.to_string());
                    blank = 0;
                }

                result.push(match piece {
                    Piece::BlackBishop => 'b',
                    Piece::BlackKing => 'k',
                    Piece::BlackKnight => 'n',
                    Piece::BlackPawn => 'p',
                    Piece::BlackQueen => 'q',
                    Piece::BlackRook => 'r',
                    Piece::WhiteBishop => 'B',
                    Piece::WhiteKing => 'K',
                    Piece::WhiteKnight => 'N',
                    Piece::WhitePawn => 'P',
                    Piece::WhiteQueen => 'Q',
                    Piece::WhiteRook => 'R',
                });
            },
        };

        match index {
            0 | 3 | 8 | 15 | 24 | 35 | 46 | 57 | 68 | 79 => {
                if blank > 0 {
                    result.push_str(&blank.to_string());
                }

                result.push('/');
                blank = 0;
            },
            _ => {}
        };

        index += 1;
    }

    if blank > 0 {
        result.push_str(&blank.to_string());
    }

    result
}

/// convert character to piece
fn to_piece(source: char) -> Result<Piece, &'static str> {
    match source {
        'p' => Ok(Piece::BlackPawn),
        'n' => Ok(Piece::BlackKnight),
        'b' => Ok(Piece::BlackBishop),
        'r' => Ok(Piece::BlackRook),
        'q' => Ok(Piece::BlackQueen),
        'k' => Ok(Piece::BlackKing),
        'P' => Ok(Piece::WhitePawn),
        'N' => Ok(Piece::WhiteKnight),
        'B' => Ok(Piece::WhiteBishop),
        'R' => Ok(Piece::WhiteRook),
        'Q' => Ok(Piece::WhiteQueen),
        'K' => Ok(Piece::WhiteKing),
        _ => Err("invalid_piece_character")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::hash::{DefaultHasher, Hasher};

    #[test]
    fn test_clone() {
        let hexchess = Hexchess::init();
        let clone = hexchess.clone();

        assert_eq!(clone.board, hexchess.board);
        assert_eq!(clone.ep, hexchess.ep);
        assert_eq!(clone.turn, hexchess.turn);
        assert_eq!(clone.halfmove, hexchess.halfmove);  
        assert_eq!(clone.fullmove, hexchess.fullmove);
    }

    #[test]
    fn test_hash_equality() {
        let hexchess1 = Hexchess::init();
        let hexchess2 = Hexchess::init();

        assert_eq!(hexchess1, hexchess2);

        let mut hasher1 = DefaultHasher::new();
        let mut hasher2 = DefaultHasher::new();
        hexchess1.hash(&mut hasher1);
        hexchess2.hash(&mut hasher2);

        assert_eq!(hasher1.finish(), hasher2.finish());
    }

    #[test]
    fn test_to_piece() {
        assert_eq!(to_piece('b'), Ok(Piece::BlackBishop));
        assert_eq!(to_piece('B'), Ok(Piece::WhiteBishop));
        assert_eq!(to_piece('k'), Ok(Piece::BlackKing)); // <- not called during normal board parsing
        assert_eq!(to_piece('K'), Ok(Piece::WhiteKing)); // <- not called during normal board parsing
        assert_eq!(to_piece('n'), Ok(Piece::BlackKnight));
        assert_eq!(to_piece('N'), Ok(Piece::WhiteKnight));
        assert_eq!(to_piece('p'), Ok(Piece::BlackPawn));
        assert_eq!(to_piece('P'), Ok(Piece::WhitePawn));
        assert_eq!(to_piece('q'), Ok(Piece::BlackQueen));
        assert_eq!(to_piece('Q'), Ok(Piece::WhiteQueen));
        assert_eq!(to_piece('r'), Ok(Piece::BlackRook));
        assert_eq!(to_piece('R'), Ok(Piece::WhiteRook));
    }

    #[test]
    fn test_to_piece_invalid() {
        assert_eq!(to_piece('x'), Err("invalid_piece_character"));
        assert_eq!(to_piece('1'), Err("invalid_piece_character"));
        assert_eq!(to_piece('/'), Err("invalid_piece_character"));
        assert_eq!(to_piece(' '), Err("invalid_piece_character"));
    }
}