aboutsummaryrefslogtreecommitdiff
path: root/src/grossmeister/UCI.rs
blob: 1bd5f92ffaab84043cbea268851383a4684a0591 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
use std::{io::stdin, thread::{JoinHandle, spawn, sleep}, str::Split, time::Duration, sync::{Arc, atomic::{AtomicBool, Ordering}}};

use crate::{board::{Board, io::IO, color::Color}, moves::{Move, MoveKind}};

use super::Grossmeister;

const NAME: &str = "Chessnost";
const AUTHOR: &str = "Eugene Sokolov";

impl Grossmeister {
    pub fn start(&mut self) {
        let mut search_handle: Option<JoinHandle<Self>> = None;

        loop {
            let mut cmd = String::new();
            stdin().read_line(&mut cmd).unwrap();
            let mut tokens = cmd.trim().split(' ');

            if let Some(token) = tokens.next() {
                match token {
                    "uci" => {
                        println!("id name {}", NAME);
                        println!("id author {}", AUTHOR);
                        println!("uciok");
                    }
                    "debug" => {
                        if let Some(token) = tokens.next() {
                            match token {
                                "on" => self.debug = true,
                                "off" => self.debug = false,
                                _ => {
                                    panic!("Wrong option to debug: {}. CMD: {}", token, cmd);
                                },
                            }
                        };
                    }
                    "isready" => {
                        println!("readyok");
                    }
                    "setoption" => {
                        todo!()
                    }
                    "ucinewgame" => {
                        *self = Self::default()
                    }
                    "position" => {
                        match tokens.next()  {
                            Some("startpos") => {
                                self.board = Board::new();
                            }
                            Some("fen") => {
                                let fen = (0..6).filter_map(|_| tokens.next()).collect::<Vec<_>>().join(" ");
                                self.board = Board::from_FEN(fen.to_string());
                            }
                            _ => panic!("Expected position"),
                        }
                        if let Some("moves") = tokens.next() {
                            for token in tokens.by_ref() {
                                let input_move = Move::from_notation(token.chars());
                                let moves = self.board.generate_pseudolegal_moves();
                                if let Some(mov) = moves
                                    .iter()
                                        .find(|m| {
                                            let promo_matches = match input_move.kind {
                                                MoveKind::Promotion(piece) => match m.kind {
                                                    MoveKind::Promotion(another_piece) => piece.without_color() == another_piece.without_color(),
                                                    _ => false
                                                },
                                                _ => true,
                                            };
                                            promo_matches && m.source == input_move.source && m.target == input_move.target
                                        }) {
                                            self.board.make_move(*mov);
                                        } else {
                                            panic!("Illegal move: {}", input_move);
                                        }
                            }
                        }
                    }
                    "go" => {
                        // Before we go, let's join to the latest search
                        if let Some(hand) = search_handle.take() {
                            let better_self = hand.join().unwrap();
                            self.transposition_table = better_self.transposition_table;
                        }

                        search_handle = Some(self.parse_go(tokens, false));
                    }
                    "stop" => {
                        self.should_halt.store(true, std::sync::atomic::Ordering::SeqCst);
                    }
                    "ponderhit" => {
                        // Since we were pondering without any scheduled halting previously,
                        // in case of ponderhit we need to schedule a new halting based on clock
                        // TODO: isn't the color flipped here? Might lead to time management bugs
                        let color = self.board.color();
                        let duration = (self.board.clock.time[color as usize] + self.board.clock.increment[color as usize]) / 20;
                        let halt_scheduled = self.schedule_halt(duration);

                        // Join to the current pondering search
                        if let Some(hand) = search_handle.take() {
                            hand.join().unwrap();
                            halt_scheduled.store(false, Ordering::SeqCst); // Cancel scheduled halting
                        } else {
                            panic!("Search thread not found!");
                        }
                    }
                    "quit" => break,
                    _ => {},
                }
            }
        }
    }

    fn parse_go(&mut self, mut tokens: Split<char>, ponder: bool) -> JoinHandle<Self> {
        if let Some(token) = tokens.next() {
            match token {
                "searchmoves" => todo!(),
                "ponder" => {
                    println!("info will start in pondering mode");
                    return self.parse_go(tokens, true)
                }
                "wtime" => {
                    if let Some(time) = tokens.next() {
                        let time: u64 = time.parse().unwrap();
                        self.board.clock.time[Color::White as usize] = Duration::from_millis(time);
                    }
                }
                "btime" => {
                    if let Some(time) = tokens.next() {
                        let time: u64 = time.parse().unwrap();
                        self.board.clock.time[Color::Black as usize] = Duration::from_millis(time);
                    }
                }
                "winc" => {
                    if let Some(time) = tokens.next() {
                        let time: u64 = time.parse().unwrap();
                        self.board.clock.increment[Color::White as usize] = Duration::from_millis(time);
                    }
                }
                "binc" => {
                    if let Some(time) = tokens.next() {
                        let time: u64 = time.parse().unwrap();
                        self.board.clock.increment[Color::Black as usize] = Duration::from_millis(time);
                    }
                }
                "movestogo" => {}
                "depth" => {
                    if let Some(depth) = tokens.next() {
                        let depth: u8 = depth.parse().unwrap();
                        return self.create_search_thread(depth, Duration::MAX);
                    }
                },
                "nodes" => todo!(),
                "mate" => todo!(),
                "movetime" => {
                    if let Some(time) = tokens.next() {
                        let time: u64 = time.parse().unwrap();
                        let duration = Duration::from_millis(time);

                        return self.create_search_thread(u8::MAX, duration)
                    }
                },
                "infinite" => {
                    return self.create_search_thread(u8::MAX, Duration::MAX);
                },
                _ => {}
            }
            return self.parse_go(tokens, ponder);
        }

        let color = self.board.color();

        let duration = if ponder {
            Duration::MAX
        } else {
            (self.board.clock.time[color as usize] + self.board.clock.increment[color as usize]) / 20
        };

        self.create_search_thread(u8::MAX, duration)
    }

    fn schedule_halt(&self, duration: Duration) -> Arc<AtomicBool> {
        let halt_scheduled = Arc::new(AtomicBool::new(false));

        if duration < Duration::MAX {
            halt_scheduled.store(true, Ordering::SeqCst);
            let should_halt = self.should_halt.clone();

            // Create a thread that will terminate search when the duration is expired
            let halt_scheduled = halt_scheduled.clone();
            spawn(move || {
                println!("info string terminating search in {:?}", duration);
                sleep(duration);
                // Make sure schedule is not cancelled externally
                if halt_scheduled.load(Ordering::SeqCst) {
                    should_halt.store(true, Ordering::SeqCst);
                }
            });
        }

        halt_scheduled
    }

    fn create_search_thread(&self, depth: u8, duration: Duration) -> JoinHandle<Self> {
        // Make sure we don't halt right away
        self.should_halt.store(false, Ordering::SeqCst);

        let halt_scheduled = self.schedule_halt(duration);

        // Clone current self and move it into thread to analyze a position
        let mut gm = self.clone();
        spawn(move || {
            gm.iterative_deepening(depth);
            halt_scheduled.store(false, Ordering::SeqCst); // Cancel the scheduled halting
            gm // Return better version of Self
        })
    }
}