engine.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. use bitboard::Bitboard;
  2. use game::Game;
  3. use search::*;
  4. use movegen::*;
  5. use evaluate::PosValue;
  6. use log::{info};
  7. use std::time::{Duration, Instant};
  8. use std::collections::{VecDeque};
  9. use zobrist::ZobristTable;
  10. use hash::{Cache, RepetitionTable};
  11. use std::sync::Arc;
  12. use std::sync::mpsc::{Receiver, Sender};
  13. pub enum EngineMsg {
  14. SetBoard{ pos: Game, moves: Vec<String> },
  15. SetPiece(Bitboard),
  16. Search(SearchInfo),
  17. Print,
  18. IsReady,
  19. Ping,
  20. Stop,
  21. NewGame,
  22. GetState,
  23. GetInfo,
  24. }
  25. pub struct SearchInfo {
  26. pub depth: Option<i32>,
  27. pub movetime: Option<i32>,
  28. pub wtime: Option<isize>,
  29. pub btime: Option<isize>,
  30. pub winc: Option<isize>,
  31. pub binc: Option<isize>,
  32. pub movestogo: Option<isize>,
  33. pub perft: bool,
  34. pub infinite: bool
  35. }
  36. pub enum InterfaceMsg {
  37. }
  38. pub struct Engine {
  39. game: Game,
  40. move_history: RepetitionTable,
  41. messages: VecDeque<EngineMsg>,
  42. r: Receiver<EngineMsg>,
  43. #[allow(unused)]
  44. s: Sender<InterfaceMsg>,
  45. hash: Cache,
  46. zobrist_table: Arc<ZobristTable>
  47. }
  48. impl SearchInfo {
  49. pub fn new() -> Self {
  50. SearchInfo {
  51. depth: None,
  52. movetime: None,
  53. wtime: None,
  54. btime: None,
  55. winc: None,
  56. binc: None,
  57. movestogo: None,
  58. perft: false,
  59. infinite: false
  60. }
  61. }
  62. }
  63. impl Engine {
  64. pub fn new(r: Receiver<EngineMsg>, s: Sender<InterfaceMsg>) -> Self {
  65. let mut eng = Engine {
  66. game: Game::default(),
  67. move_history: RepetitionTable::new(),
  68. messages: VecDeque::new(),
  69. r, s,
  70. hash: Cache::new(),
  71. zobrist_table: Arc::new(ZobristTable::new())
  72. };
  73. eng.game.zobrist = Some((eng.zobrist_table.clone(), eng.game.calculate_zobrist(&eng.zobrist_table)));
  74. eng
  75. }
  76. pub fn run(&mut self) {
  77. while let Some(msg) = self.dequeue_message() {
  78. match msg {
  79. EngineMsg::SetBoard{ pos, moves } => {
  80. self.set_position(pos, &moves);
  81. },
  82. EngineMsg::Search(ref info) => {
  83. self.start_search(info);
  84. },
  85. EngineMsg::Print => {
  86. println!("{}", self.game.beautiful_print());
  87. },
  88. EngineMsg::IsReady => {
  89. println!("readyok");
  90. }
  91. _ => {}
  92. }
  93. }
  94. }
  95. fn set_position(&mut self, pos: Game, moves: &Vec<String>) {
  96. self.game = pos;
  97. self.game.zobrist = Some((self.zobrist_table.clone(), self.game.calculate_zobrist(&self.zobrist_table)));
  98. self.move_history.clear();
  99. self.move_history.increment(self.game.calculate_zobrist(&self.zobrist_table));
  100. for mov in moves {
  101. let m = self.game.parse_move(&mov);
  102. if let Ok(mm) = m {
  103. self.game.apply(mm);
  104. self.move_history.increment(self.game.calculate_zobrist(&self.zobrist_table));
  105. }
  106. else {
  107. println!("{}", self.game.beautiful_print());
  108. println!("error parsing move {}", mov);
  109. break;
  110. }
  111. }
  112. }
  113. /**
  114. * blocks until a message is available
  115. */
  116. fn dequeue_message(&mut self) -> Option<EngineMsg> {
  117. if self.messages.is_empty() {
  118. self.r.recv().ok()
  119. }
  120. else {
  121. self.messages.pop_front()
  122. }
  123. }
  124. #[allow(unused)]
  125. fn try_dequeue_message(&mut self) -> Option<EngineMsg> {
  126. if self.messages.is_empty() {
  127. self.r.try_recv().ok()
  128. }
  129. else {
  130. self.messages.pop_front()
  131. }
  132. }
  133. fn start_search(&mut self, si: &SearchInfo) {
  134. if let None = self.game.zobrist {
  135. self.game.zobrist = Some((self.zobrist_table.clone(), self.game.calculate_zobrist(&self.zobrist_table)));
  136. }
  137. let side = self.game.turn;
  138. let receiver = &mut self.r;
  139. let messages = &mut self.messages;
  140. let before = Instant::now();
  141. let mut depth = 1;
  142. let mut check_fn =
  143. || -> bool {
  144. if !messages.is_empty() {
  145. if let EngineMsg::Stop = messages[0] {
  146. return true;
  147. }
  148. }
  149. if let Ok(msg) = receiver.try_recv() {
  150. if let EngineMsg::Stop = msg {
  151. messages.push_back(msg);
  152. return true;
  153. }
  154. if let EngineMsg::IsReady = msg {
  155. println!("readyok");
  156. return false;
  157. }
  158. else {
  159. messages.push_back(msg);
  160. }
  161. }
  162. if let Some(millis) = si.movetime {
  163. if before.elapsed() > Duration::from_millis(millis as _) {
  164. return true;
  165. }
  166. }
  167. else if side == WHITE {
  168. if let Some(wtime) = si.wtime {
  169. if before.elapsed() > Duration::from_millis((wtime / 35) as _) {
  170. return true;
  171. }
  172. }
  173. }
  174. else if side == BLACK {
  175. if let Some(btime) = si.btime {
  176. if before.elapsed() > Duration::from_millis((btime / 35) as _) {
  177. return true;
  178. }
  179. }
  180. }
  181. return false;
  182. };
  183. let mut sc = SearchControl::new(&mut check_fn, &mut self.move_history, 0);
  184. let mut best_move = Move::default();
  185. let mut best_val: PosValue;
  186. if si.perft {
  187. if let Some(dep) = si.depth {
  188. depth = dep;
  189. }
  190. let invalid = perft(&mut self.game, &mut sc, depth as i32);
  191. if !invalid {
  192. let elapsed = before.elapsed();
  193. let nodes = sc.nodes;
  194. let nps = (nodes as f64 / elapsed.as_nanos() as f64 * 1000000000.0) as i64;
  195. println!("info depth {} nodes {} nps {}", depth, nodes, nps);
  196. }
  197. return;
  198. }
  199. let mut alpha = crate::evaluate::MIN_VALUE;
  200. let mut beta = crate::evaluate::MAX_VALUE;
  201. let window_size = 100;
  202. loop {
  203. sc.initial_depth = depth;
  204. sc.pv = vec![Move::Nullmove; depth as _];
  205. let search_result = search(&mut self.game, &mut sc, &mut self.hash, alpha, beta, depth as i32);
  206. if let SearchResult::Finished(bm, bv) = search_result {
  207. info!("depth: {} bm: {}, bv: {}", depth, bm.to_string(), bv);
  208. if bv >= beta || bv <= alpha {
  209. alpha = crate::evaluate::MIN_VALUE;
  210. beta = crate::evaluate::MAX_VALUE;
  211. //println!("repeat");
  212. continue;
  213. }
  214. else {
  215. alpha = bv - window_size;
  216. beta = bv + window_size;
  217. }
  218. best_move = bm;
  219. best_val = bv;
  220. let elapsed = before.elapsed();
  221. let nodes = sc.nodes;
  222. let nps = (nodes as f64 / elapsed.as_nanos() as f64 * 1000000000.0) as i64;
  223. let cp = best_val as i64;
  224. let pv = &sc.pv.iter().filter(|&m| !m.is_null()).map(|m| m.to_string()).fold(String::new(), |a, b| a + " " + &b)[1..];
  225. if let Some(plies) = crate::evaluate::is_mate_in_p1(bv) {
  226. let turns = plies / 2;
  227. println!("info depth {} score mate {} time {} nodes {} nps {} pv {}", depth, turns, elapsed.as_millis(), nodes, nps, pv);
  228. info!("info depth {} score mate {} time {} nodes {} nps {} pv {}", depth, turns, elapsed.as_millis(), nodes, nps, pv);
  229. /*if depth > 3 {
  230. break;
  231. }*/
  232. /*if plies.abs() * 3 < depth {
  233. break;
  234. }*/
  235. }
  236. else {
  237. println!("info depth {} score cp {} time {} nodes {} nps {} pv {}", depth, cp, elapsed.as_millis(), nodes, nps, pv);
  238. info!("info depth {} score cp {} time {} nodes {} nps {} pv {}", depth, cp, elapsed.as_millis(), nodes, nps, pv);
  239. }
  240. depth += 1;
  241. }
  242. else if let SearchResult::Cancelled(Some((bm, bv))) = search_result {
  243. if best_move == Move::Nullmove {
  244. best_move = bm;
  245. //best_val = bv;
  246. }
  247. break;
  248. }
  249. else {
  250. break;
  251. }
  252. if let Some(d) = si.depth {
  253. if depth > d {
  254. break;
  255. }
  256. }
  257. }
  258. info!("bestmove {}", best_move.to_string());
  259. println!("bestmove {}", best_move.to_string());
  260. }
  261. }
  262. /*
  263. fn dequeue_message(queue: &mut VecDeque<EngineMsg>, r: &Receiver<EngineMsg>) -> Option<EngineMsg> {
  264. if queue.is_empty() {
  265. r.recv().ok()
  266. }
  267. else {
  268. queue.pop_front()
  269. }
  270. }
  271. pub fn run_engine(r: Receiver<EngineMsg>, _s: Sender<InterfaceMsg>) {
  272. let mut game = Game::default();
  273. let mut messages: VecDeque<EngineMsg> = VecDeque::new();
  274. loop {
  275. let msg = dequeue_message(&mut messages, &r).unwrap();
  276. match msg {
  277. EngineMsg::SetBoard(g) => {
  278. game = g;
  279. },
  280. EngineMsg::SetPiece(_) => { println!("SetPiece") },
  281. EngineMsg::Search(info) => {
  282. match info {
  283. SearchInfo::Depth(depth) => {
  284. let mut check_fn = || -> bool {
  285. if let Ok(msg) = r.try_recv() {
  286. if let EngineMsg::Stop = msg {
  287. return true;
  288. }
  289. else {
  290. messages.push_back(msg);
  291. }
  292. }
  293. return false;
  294. };
  295. let mut sc = SearchControl{ nodes: 0, check: &mut check_fn };
  296. let before = Instant::now();
  297. let best_move = search(&game, &mut sc, depth as i32);
  298. let time = before.elapsed();
  299. let nps = (sc.nodes as f64 / time.as_millis() as f64 * 1000.0) as i64;
  300. info!("bestmove {}", best_move.to_string());
  301. info!("searched {} nodes in {} ms ({} nodes/s)", sc.nodes, time.as_millis(), (sc.nodes as f64 / time.as_millis() as f64 * 1000.0) as i64);
  302. println!("info nps {}", nps.to_string());
  303. println!("bestmove {}", best_move.to_string());
  304. },
  305. SearchInfo::Movetime(millis) => {
  306. let before = Instant::now();
  307. let mut depth = 1;
  308. let mut check_fn = || -> bool {
  309. if let Ok(msg) = r.try_recv() {
  310. if let EngineMsg::Stop = msg {
  311. return true;
  312. }
  313. else {
  314. messages.push_back(msg);
  315. }
  316. }
  317. if before.elapsed() > Duration::from_millis(millis as _) {
  318. return true;
  319. }
  320. return false;
  321. };
  322. let mut sc = SearchControl{ nodes: 0, check: &mut check_fn };
  323. let mut best_move = Move::default();
  324. loop {
  325. let bm = search(&game, &mut sc, depth as i32);
  326. if bm != Move::default() {
  327. best_move = bm;
  328. }
  329. else {
  330. break;
  331. }
  332. depth += 1;
  333. }
  334. println!("bestmove {}", best_move.to_string());
  335. },
  336. _ => {}
  337. }
  338. },
  339. EngineMsg::Ping => { println!("Ping") },
  340. EngineMsg::Stop => { println!("Stop") },
  341. EngineMsg::NewGame => {
  342. //println!("NewGame")
  343. },
  344. EngineMsg::GetState => { println!("GetState") },
  345. EngineMsg::GetInfo => { println!("GetInfo") },
  346. }
  347. //println!("{}", game.beautiful_print());
  348. //let moves = generate_moves(&game, WHITE);
  349. }
  350. }
  351. */