chess_uci/chess_uci/src/lib.rs

193 lines
5.9 KiB
Rust
Raw Normal View History

#![allow(dead_code)]
/// Manage UCI messages and link into chess component
2023-01-11 12:07:28 +01:00
mod uci_command;
2023-01-11 17:18:15 +01:00
use log::{info, warn};
2023-01-11 12:07:28 +01:00
use std::io::*;
use crate::uci_command::*;
2023-01-11 18:20:30 +01:00
use chess::{Game, Board, ChessMove};
2023-01-13 11:54:28 +01:00
/// Structure used to manage a chess game with a uci engine.
///
/// It needs a in / out communication channel to read / push line by line uci commands
///c
/// ```rust
/// use chess_uci::UciEngine;
/// use std::process::{Command, Stdio};
/// use std::io::BufReader;
///
/// let process = match Command::new("stockfish")
/// .stdin(Stdio::piped())
/// .stdout(Stdio::piped())
/// .spawn() {
/// Err(why) => panic!("couldn't spawn stockfish: {}", why),
/// Ok(process) => process,
/// };
/// let (sf_in,sf_out) = (process.stdin.expect("Program stdin"), process.stdout.expect("Program stdout"));
///
/// let mut uci = UciEngine::new(BufReader::new(sf_out), sf_in);
/// // .. uci.init(); ..
/// uci.push_raw("quit\n");
/// ```
pub struct UciEngine<Fi: Read, Fo: Write> {
source: BufReader<Fi>,
2023-01-11 12:07:28 +01:00
destination: Fo,
uciok: bool,
id: Id,
2023-01-11 18:20:30 +01:00
initial: Board,
game: Game,
2023-01-11 12:07:28 +01:00
}
impl<Fi: Read, Fo: Write> UciEngine<Fi, Fo> {
2023-01-13 11:54:28 +01:00
/// Create new game manager
///
/// Requires line by line input and output streams to communicate with uci engine
2023-01-11 12:07:28 +01:00
pub fn new(source: Fi, destination: Fo) -> UciEngine<Fi, Fo> {
UciEngine::<Fi, Fo>{
source: BufReader::new(source),
destination,
2023-01-11 17:18:15 +01:00
id: Id::new(),
2023-01-11 18:20:30 +01:00
uciok: false,
initial: Board::default(),
game: Game::new()
}
2023-01-11 12:07:28 +01:00
}
2023-01-13 11:54:28 +01:00
/// Launch uci engine initialisation
///
/// Retrieve data from uci engine (until uciok command from engine)
2023-01-11 17:18:15 +01:00
pub fn init(&mut self){
self.push(GuiCommand::Uci);
// Consume commands until uciok messages
while !self.uciok {
self.pull();
}
}
2023-01-13 11:54:28 +01:00
/// Initialize a new game
///
/// Set a new board internally and tell the engine
2023-01-11 17:18:15 +01:00
pub fn new_game(&mut self) {
2023-01-11 18:20:30 +01:00
self.initial = Board::default();
self.game = Game::new_with_board(self.initial);
self.push(GuiCommand::UciNewGame);
}
2023-01-13 11:54:28 +01:00
/// Play a move
///
/// Update internal game reference and tell the uci engine
///
/// ```rust
/// use chess::ChessMove;
/// use std::str::FromStr;
/// use chess_uci::*;
/// use std::io;
///
/// let mut uci = UciEngine::new(io::empty(), io::sink());
///
/// uci.make_move(ChessMove::from_str("e2e4").expect("error converting e2e4"));
/// ```
2023-01-11 18:20:30 +01:00
pub fn make_move(&mut self, chess_move: ChessMove) {
self.game.make_move(chess_move);
self.push(GuiCommand::Position { position: Some(self.initial), moves: self.game.actions().to_vec() })
2023-01-11 17:18:15 +01:00
}
2023-01-13 11:54:28 +01:00
fn terminate(&mut self, reason: &str) {
2023-01-11 17:18:15 +01:00
self.uciok = false;
info!("UCI termination: {}", reason);
}
2023-01-13 11:54:28 +01:00
/// Provides the name of the uci engine
2023-01-11 12:07:28 +01:00
pub fn name(&self) -> Option<String> {
self.id.name()
}
2023-01-13 11:54:28 +01:00
/// Provides the author sof the uci engine
2023-01-11 12:07:28 +01:00
pub fn author(&self) -> Option<String> {
self.id.author()
}
2023-01-13 11:54:28 +01:00
fn update(&mut self, id: &Id){
2023-01-11 12:07:28 +01:00
if self.is_uciok() {warn!("Engine info should not be updated now (uciok)");}
self.id.update(id);
}
2023-01-11 17:18:15 +01:00
2023-01-13 11:54:28 +01:00
fn update_from_str(&mut self, name: Option<&str>, author: Option<&str>){
2023-01-11 12:07:28 +01:00
if self.is_uciok() {warn!("Engine info should not be updated now (uciok)");}
self.id.update_from_str(name, author);
}
2023-01-13 11:54:28 +01:00
fn uciok(&mut self){
2023-01-11 12:07:28 +01:00
self.uciok = true;
}
2023-01-13 11:54:28 +01:00
/// Tell whether the uci engine has initialized
2023-01-11 12:07:28 +01:00
pub fn is_uciok(&self) -> bool {
self.uciok
}
2023-01-13 11:54:28 +01:00
/// Execute a uci command
///
2023-01-13 11:54:28 +01:00
/// if `EngineCommand::Id`: update name or authorship of the engine
/// if `EngineCommand::UciOk`: end engine initialization phase
2023-01-11 12:07:28 +01:00
pub fn exec(&mut self, command: &str){
match parse (&mut command.to_string()) {
Ok(EngineCommand::Id{id}) => self.update(&id),
Ok(EngineCommand::UciOk) => self.uciok(),
2023-01-11 17:18:15 +01:00
Ok(EngineCommand::Opt { options: _ }) => {},
2023-01-11 12:07:28 +01:00
Ok(_) => {unimplemented!("command not implemented")},
Err(_) => warn!("Not a command"),
}
}
2023-01-13 11:54:28 +01:00
/// Retrieve a line from the uci engine input stream and parse it
2023-01-11 17:18:15 +01:00
pub fn pull(&mut self) {
2023-01-11 17:18:15 +01:00
let mut command = String::new();
match self.source.read_line(&mut command) {
Ok(0) => self.terminate("Chess engine closed connection."),
Ok(_) => {
info!("← {}", command);
self.exec(&command)
},
Err(reason) => warn!("Unable to read from engine: {reason}"),
}
}
2023-01-13 11:54:28 +01:00
/// Read a line from the uci engine input stream (do not parse)
2023-01-12 17:27:17 +01:00
pub fn pull_raw(&mut self) -> Option<String> {
let mut data = String::new();
match self.source.read_line(&mut data) {
Ok(0) => {self.terminate("Chess engine closed connection."); None},
Ok(_) => {info!("↜ {}", data); Some(data.clone())},
Err(reason) => {warn!("Unable to read from engine: {reason}"); None},
}
}
2023-01-13 11:54:28 +01:00
/// Push a Uci Gui command to the engine
fn push(&mut self, command: GuiCommand) {
2023-01-11 17:18:15 +01:00
let command_str = command.to_string();
match self.destination.write(&command_str.as_bytes()){
2023-01-12 17:27:17 +01:00
Ok(n) if n == command_str.len() => info!("→ gui: {command_str}"),
2023-01-11 17:18:15 +01:00
Ok(n) => warn!("⚠ gui: {command_str} truncated at {n}"),
Err(reason) => warn!("Unable to send command {command_str}: {reason}"),
}
}
2023-01-12 17:27:17 +01:00
2023-01-13 11:54:28 +01:00
/// Push string (not a game manager integrated command) to the Uci engine output stream
2023-01-12 17:27:17 +01:00
pub fn push_raw(&mut self, data: &str){
match self.destination.write(data.as_bytes()) {
Ok(n) if n == data.len() => info!("↝ raw: {data}"),
Ok(n) => warn!("⚠ raw: {data} truncated at {n}"),
Err(reason) => warn!("Unable to send raw {data}: {reason}"),
}
}
}
2023-01-13 11:54:28 +01:00
// LocalWords: uci