stellar

UCI Chess engine written in C++20
git clone git://git.dimitrijedobrota.com/stellar.git
Log | Files | Refs | README | LICENSE

board.cpp (2708B)


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