Skip to content
This repository has been archived by the owner on Oct 8, 2024. It is now read-only.

Commit

Permalink
refactor: lots of code cleanups and stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
dannyhammer committed Aug 23, 2024
1 parent 1ec2817 commit 4a46595
Show file tree
Hide file tree
Showing 15 changed files with 421 additions and 588 deletions.
74 changes: 5 additions & 69 deletions brogle/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,48 +14,17 @@ use brogle_core::{print_perft, Bitboard, Color, Game, Move, Position, Tile, FEN_
use log::{error, warn};
use threadpool::ThreadPool;

use crate::search::DEFAULT_TTABLE_SIZE;

use super::{
protocols::{
UciCommand, UciEngine, UciInfo, UciOption, UciResponse, UciScore, UciSearchOptions,
},
search::{Searcher, TTable},
search::{Searcher, TTable, DEFAULT_TTABLE_SIZE},
Evaluator, MATE, MAX_DEPTH, MAX_MATE,
};

/// Threadpool from which to spawn threads for searches, user input, etc.
pub static POOL: LazyLock<ThreadPool> = LazyLock::new(|| ThreadPool::new(num_cpus::get()));

/// Represents the possible communication protocols supported by this engine.
///
/// Presently, only [UCI](https://backscattering.de/chess/uci/) is supported.
#[derive(PartialEq, Eq, Clone, Copy, Debug, Hash, Default)]
enum EngineProtocol {
#[default]
Uci,
}

/*
pub enum ScoreBound {
// The score is exact
Exact,
/// The score is less than alpha
Upper,
/// The score is greater than or equal to beta
Lower,
}
pub struct TranspositionTableEntry {
key: u64,
bestmove: Move,
depth: usize,
score: i32,
score_bound: ScoreBound,
age: usize,
}
*/

/// A chess engine responds to inputs (such as from a GUI or terminal) and
/// responds with computed outputs. The most common modern protocol is UCI.
///
Expand Down Expand Up @@ -88,9 +57,6 @@ pub struct Engine {

/// Handles sending events to the internal event pump.
sender: Option<Sender<EngineCommand>>,
//
// /// List of available configuration options
// options: todo!(),
}

impl Engine {
Expand Down Expand Up @@ -133,7 +99,6 @@ impl Engine {
let res = match cmd {
EngineCommand::Help => self.help(),
EngineCommand::Show => self.show(),
EngineCommand::History => self.history(),
EngineCommand::Perft {
depth,
pretty,
Expand All @@ -144,7 +109,6 @@ impl Engine {
EngineCommand::Moves(from, debug) => self.moves(from, debug),
EngineCommand::Bench => todo!("Implement `bench` command"),
EngineCommand::MakeMove(moves) => self.make_move(moves),
EngineCommand::Undo => self.undo(),
EngineCommand::Option(name) => self.option(name),
EngineCommand::UciCommand(uci_cmd) => self.execute_uci_command(uci_cmd),
EngineCommand::UciResponse(uci_resp) => self.send_uci_response(*uci_resp),
Expand Down Expand Up @@ -234,14 +198,12 @@ impl Engine {
match cmd {
"help" => Ok(EngineCommand::Help),
"show" => Ok(EngineCommand::Show),
"history" => Ok(EngineCommand::History),
"perft" => Self::parse_perft_command(rest),
"eval" => Self::parse_eval_command(rest),
"move" => Self::parse_move_command(rest),
"moves" => Self::parse_moves_command(rest),
"fen" => Self::parse_fen_command(rest),
"option" => Self::parse_option_command(rest),
"undo" => Ok(EngineCommand::Undo),
"bench" => Ok(EngineCommand::Bench),
"quit" | "exit" => Ok(EngineCommand::Exit),
_ => Self::parse_uci_input(input).map(EngineCommand::UciCommand),
Expand Down Expand Up @@ -365,7 +327,9 @@ impl Engine {

/// Executes the `help` command, displaying a list of available commands this engine has.
fn help(&self) -> Result<()> {
println!("available commands: help, perft, show, history, fen, move, moves, eval, uci, bench, undo");
println!(
"available commands: help, perft, show, option, fen, move, moves, eval, uci, bench"
);
Ok(())
}

Expand All @@ -375,22 +339,6 @@ impl Engine {
Ok(())
}

/// Executes the `history` command, printing all moves made on this current game.
fn history(&self) -> Result<()> {
// TODO: Replace with to_pgn function
println!(
"{}",
self.game
.history()
.iter()
.enumerate()
.map(|(i, m)| format!("{}) {m}", i + 1))
.collect::<Vec<_>>()
.join(" ")
);
Ok(())
}

/// Executes the `perft` command, performing `perft(depth)` for benchmarking and testing.
pub fn perft(&self, depth: usize, pretty: bool, split: bool) -> Result<()> {
// Man, I wish I could just pass `split` and `pretty` in directly
Expand Down Expand Up @@ -469,12 +417,6 @@ impl Engine {
Ok(())
}

/// Executes the `undo` command, un-making the previously-made move.
fn undo(&mut self) -> Result<()> {
self.game.unmake_move();
Ok(())
}

/// Executes the `option` command, displaying the current value of a provided engine option.
fn option(&self, name: String) -> Result<()> {
println!("{name}=UNSET");
Expand Down Expand Up @@ -515,9 +457,6 @@ pub enum EngineCommand {
/// Pretty-print the current state of the board.
Show,

/// Display the moves made during this game.
History,

/// Show the current state of of the board as a FEN string.
Fen(Option<String>),

Expand All @@ -533,9 +472,6 @@ pub enum EngineCommand {
/// Benchmark this engine.
Bench,

/// Undo the last move made.
Undo,

/// View the current value of an option
Option(String),

Expand Down Expand Up @@ -692,7 +628,7 @@ impl UciEngine for Engine {
.nps((data.nodes_searched as f32 / elapsed.as_secs_f32()).trunc())
.time(elapsed.as_millis())
.pv(data.bestmove);
// .pv(&data.pv[0]);
// .pv(&data.pv[0]);

let info_resp = Box::new(UciResponse::Info(Box::new(info)));
if let Err(err) = sender.send(EngineCommand::UciResponse(info_resp)) {
Expand Down
4 changes: 2 additions & 2 deletions brogle/src/eval/piece_square_tables.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::fmt;

use brogle_core::{Color, File, Piece, PieceKind, Rank, Tile, NUM_TILES};
use brogle_core::{Color, File, Piece, PieceKind, Rank, Tile};

#[rustfmt::skip]
const PAWNS: Psq = Psq([
Expand Down Expand Up @@ -91,7 +91,7 @@ const KING_EG: Psq = Psq([
/// When defining a PSQ, the table as-written in code will apply for White.
/// That is, the lowest 8 indices correspond to the first rank, and so on.
#[derive(PartialEq, Eq, Debug)]
struct Psq([i32; NUM_TILES]);
struct Psq([i32; Tile::COUNT]);

impl Psq {
/// Get the value of this PSQ at the provided tile.
Expand Down
4 changes: 0 additions & 4 deletions brogle/src/search/searcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ pub struct SearchData {

/// Score for making the associated `bestmove`.
pub score: i32,

/*
/// Principle Variation of the search.
///
Expand Down Expand Up @@ -199,7 +198,6 @@ impl<'a> Searcher<'a> {
}

// Check for mate in qsearch if and only if we're in check.
/*
let mut moves = if game.is_in_check() {
let moves = game.legal_moves();

Expand All @@ -219,8 +217,6 @@ impl<'a> Searcher<'a> {

captures
};
*/
let mut moves = game.legal_captures();

// Can't check for mates in normal qsearch, since we're not looking at *all* moves.
if moves.is_empty() {
Expand Down
2 changes: 1 addition & 1 deletion brogle/src/search/transposition_table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ pub struct TTableEntry {
}

/// Default size of the Transposition Table, in bytes
pub(crate) const DEFAULT_TTABLE_SIZE: usize = 1_048_576; // 1 mb
pub(crate) const DEFAULT_TTABLE_SIZE: usize = 16_777_216; // 16 mb

/// Transposition Table
#[derive(Debug)]
Expand Down
12 changes: 1 addition & 11 deletions brogle_core/brogle_types/src/bitboard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ impl Bitboard {
/// assert_eq!(invalid.to_tile(), None);
/// ```
pub const fn to_tile(&self) -> Option<Tile> {
if self.is_only_one() {
if self.population() == 1 {
Some(self.to_tile_unchecked())
} else {
None
Expand Down Expand Up @@ -307,16 +307,6 @@ impl Bitboard {
self.0 != 0
}

/// Returns `true` if this [`Bitboard`] has at most `n` bits set.
pub const fn is_at_most(&self, n: u8) -> bool {
self.population() <= n
}

/// Returns `true` if this [`Bitboard`] has exactly `1` bit set.
pub const fn is_only_one(&self) -> bool {
self.population() == 1
}

/// Checks if this [`Bitboard`] contains any of the bits within `other`.
///
/// # Example
Expand Down
Loading

0 comments on commit 4a46595

Please sign in to comment.