[explorer, perft, position] Move node count into a new PerftCounters struct

This commit is contained in:
Eryn Wells 2025-06-19 11:33:35 -07:00
parent 4ce7e89cdb
commit 0f5a538f0a
3 changed files with 47 additions and 19 deletions

View file

@ -1,20 +1,29 @@
// Eryn Wells <eryn@erynwells.me>
use chessfriend_moves::Move;
use crate::{GeneratedMove, Position, ValidateMove};
use std::fmt;
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct PerftCounters {
nodes: u64,
}
impl Position {
pub fn perft(&mut self, depth: usize) -> u64 {
self.perft_recursive(depth, depth)
pub fn perft(&mut self, depth: usize) -> PerftCounters {
self.perft_recursive(0, depth)
}
}
impl Position {
fn perft_recursive(&mut self, depth: usize, max_depth: usize) -> u64 {
if depth == 0 {
return 1;
}
fn perft_recursive(&mut self, depth: usize, max_depth: usize) -> PerftCounters {
let mut counters = PerftCounters::default();
let mut total_nodes_counted = 0u64;
if depth == max_depth {
counters.count_node();
return counters;
}
let legal_moves: Vec<GeneratedMove> = self.all_legal_moves(None).collect();
@ -25,21 +34,39 @@ impl Position {
.make_move(ply, ValidateMove::No)
.expect("unable to make generated move");
let nodes_counted = if has_seen_position {
1
let recursive_counters = if has_seen_position {
let mut counters = PerftCounters::default();
counters.count_node();
counters
} else {
self.perft_recursive(depth - 1, max_depth)
self.perft_recursive(depth + 1, max_depth)
};
total_nodes_counted += nodes_counted;
self.unmake_last_move().expect("unable to unmake last move");
if depth == max_depth {
println!(" {ply} {nodes_counted}");
counters.fold(&recursive_counters);
if depth == 0 {
println!(" {ply}: {}", recursive_counters.nodes);
}
}
total_nodes_counted
counters
}
}
impl PerftCounters {
fn count_node(&mut self) {
self.nodes += 1;
}
fn fold(&mut self, results: &Self) {
self.nodes += results.nodes;
}
}
impl fmt::Display for PerftCounters {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(f, "Perft Results")?;
write!(f, " Nodes: {}", self.nodes)
}
}