stellarUCI Chess engine written in C++20 |
git clone git://git.dimitrijedobrota.com/stellar.git |
Log | Files | Refs | README | LICENSE | |
board.cpp (2708B)
1 #include <ctype.h> 2 #include <exception> 3 #include <stdio.h> 4 #include <string.h> 5 6 #include "board.hpp" 7 #include "piece.hpp" 8 #include "square.hpp" 9 #include "utils.hpp" 10 #include "zobrist.hpp" 11 12 /* Getters */ 13 14 Board::Board(const std::string &fen) { 15 int file = 0, rank = 7, i; 16 for (i = 0; fen[i] != ' '; i++) { 17 if (isalpha(fen[i])) { 18 const piece::Piece &piece = piece::get_from_code(fen[i]); 19 set_piece(piece.type, piece.color, static_cast<square::Square>(rank * 8 + file)); 20 file++; 21 } else if (isdigit(fen[i])) { 22 file += fen[i] - '0'; 23 } else if (fen[i] == '/') { 24 if (file != 8) throw std::runtime_error("File is not complete"); 25 file = 0; 26 rank--; 27 } else { 28 throw std::runtime_error("Invalid piece position"); 29 } 30 } 31 32 side = fen[++i] == 'w' ? color::WHITE 33 : fen[i] == 'b' ? color::BLACK 34 : throw std::runtime_error("Invalid player char"); 35 36 for (i += 2; fen[i] != ' '; i++) { 37 if (fen[i] == 'K') 38 castle |= to_underlying(Castle::WK); 39 else if (fen[i] == 'Q') 40 castle |= to_underlying(Castle::WQ); 41 else if (fen[i] == 'k') 42 castle |= to_underlying(Castle::BK); 43 else if (fen[i] == 'q') 44 castle |= to_underlying(Castle::BQ); 45 else if (fen[i] == '-') { 46 i++; 47 break; 48 } else 49 throw std::runtime_error("Invalid castle rights"); 50 } 51 52 enpassant = fen[++i] != '-' ? square::from_coordinates(fen.substr(i, 2)) : square::no_sq; 53 54 hash = Zobrist::hash(*this); 55 } 56 57 std::ostream &operator<<(std::ostream &os, const Board &board) { 58 for (int rank = 0; rank < 8; rank++) { 59 for (int file = 0; file < 8; file++) { 60 if (!file) os << 8 - rank << " "; 61 square::Square square = static_cast<square::Square>((7 - rank) * 8 + file); 62 const piece::Piece *piece = board.get_square_piece(square); 63 os << (piece ? piece->code : '.') << " "; 64 } 65 printf("\n"); 66 } 67 os << " A B C D E F G H\n"; 68 os << " Side: "; 69 os << ((board.side == color::WHITE) ? "white" : "black") << "\n"; 70 os << "Enpassant: " << square::to_coordinates(board.enpassant) << "\n"; 71 os << " Castle:"; 72 os << ((board.castle & to_underlying(Board::Castle::WK)) ? 'K' : '-'); 73 os << ((board.castle & to_underlying(Board::Castle::WQ)) ? 'Q' : '-'); 74 os << ((board.castle & to_underlying(Board::Castle::BK)) ? 'k' : '-'); 75 os << ((board.castle & to_underlying(Board::Castle::BQ)) ? 'q' : '-'); 76 os << "\n Hash:" << board.hash << "\n\n"; 77 78 return os; 79 }