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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
use std::{
io,
process::Command,
sync::{mpsc, mpsc::Receiver},
time::Duration,
string::ToString,
};
use interactive_process::InteractiveProcess;
use crate::engine_eval::{EngineEval, EvalType};
use crate::engine_output::EngineOutput;
/// The interface for interacting with a Stockfish process.
pub struct Stockfish {
interactive_process: InteractiveProcess,
receiver: Receiver<String>,
depth: u32,
version: Option<String>,
}
impl Stockfish {
/// Given the path to the Stockfish binary executable, this function
/// initiates an [`InteractiveProcess`] for the executable, and returns an instance
/// of the [Stockfish] wrapper class.
///
/// # Example
///
/// ```rust
/// use stockfish::Stockfish;
/// let stockfish = Stockfish::new("stockfish.exe").unwrap();
/// ```
///
/// # Errors
///
/// Returns an [`io::Error`] if an error occurred while trying to
/// create/communicate with the engine.
pub fn new(path: &str) -> io::Result<Stockfish> {
let mut command = Command::new(path);
let (tx, rx) = mpsc::channel();
let proc = InteractiveProcess::new(&mut command, move |line| {
let line = line.unwrap();
let send_result = tx.send(line);
if send_result.is_err() {
println!("receiving end of mpsc channel disconnected");
}
})?;
let first_line = rx.recv().expect("stockfish process should have outputted a first line");
let version = first_line.split(' ').nth(1).map(ToString::to_string);
Ok(Stockfish {
interactive_process: proc,
receiver: rx,
depth: 15,
version
})
}
/// Prepares the Stockfish process for a new game. Should be called
/// to indicate to the engine that the next position it will be evaluating
/// will be from a different game.
///
/// # Example
///
/// ```rust
/// let mut stockfish = Stockfish::new("stockfish.exe")?;
/// stockfish.setup_for_new_game()?;
/// ```
///
/// # Errors
///
/// Returns an [`io::Error`] if an error occurred while trying to
/// communicate with the engine.
pub fn setup_for_new_game(&mut self) -> io::Result<()> {
self.ensure_ready()?;
self.uci_send("ucinewgame")?;
Ok(())
}
/// Changes the current chess position in which Stockfish is currently playing.
/// The argument to be passed is a string in FEN (Forsyth-Edwards Notation).
///
/// # Example
///
/// ```rust
/// let mut stockfish = Stockfish::new("stockfish.exe")?;
/// stockfish.set_fen_position("r1bqk2r/ppppppbp/2n2np1/8/8/2N2NP1/PPPPPPBP/R1BQK2R w KQkq - 0 1")?;
/// stockfish.print_board()?;
/// ```
///
/// # Errors
///
/// Returns an [`io::Error`] if an error occurred while trying to
/// communicate with the engine.
pub fn set_fen_position(&mut self, fen: &str) -> io::Result<()> {
let msg = String::from("position fen ") + fen;
self.uci_send(&msg)?;
Ok(())
}
/// Reverts the current chess position to the default starting position.
/// This is the same as calling `set_fen_position` with the default
/// fen. (`rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1`)
///
/// # Example
///
/// ```rust
/// let mut stockfish = Stockfish::new("stockfish.exe")?;
/// stockfish.set_fen_position("r1bqk2r/ppppppbp/2n2np1/8/8/2N2NP1/PPPPPPBP/R1BQK2R w KQkq - 0 1")?;
/// stockfish.reset_position()?;
///
/// // See that the board has been reverted to the default position
/// stockfish.print_board()?;
/// ```
///
/// # Errors
///
/// Returns an [`io::Error`] if an error occurred while trying to
/// communicate with the engine.
pub fn reset_position(&mut self) -> io::Result<()> {
self.uci_send("position startpos")?;
Ok(())
}
/// This should be called to ensure that the Stockfish process is ready
/// to receive its inputs. Sends the UCI command `"isready"` to Stockfish
/// and blocks until it sends back `"readyok"`.
///
/// # Example
///
/// ```rust
/// let mut stockfish = Stockfish::new("stockfish.exe")?;
/// stockfish.ensure_ready()?;
/// stockfish.setup_for_new_game()?;
/// ```
///
/// # Errors
///
/// Returns an [`io::Error`] if an error occurred while trying to
/// communicate with the engine.
pub fn ensure_ready(&mut self) -> io::Result<()> {
self.uci_send("isready")?;
while self.read_line() != "readyok" {}
Ok(())
}
/// Returns a string Forsyth-Edwards notation (FEN) describing the current chess position
/// in which Stockfish is playing.
///
/// # Example
///
/// ```rust
/// let mut stockfish = Stockfish::new("stockfish.exe")?;
/// stockfish.play_move("e2e4")?;
///
/// let fen = stockfish.get_fen()?;
/// println!("fen after move was played: {fen}");
/// ```
///
/// # Errors
///
/// Returns an [`io::Error`] if an error occurred while trying to
/// communicate with the engine.
pub fn get_fen(&mut self) -> io::Result<String> {
self.uci_send("d")?;
loop {
let line = self.read_line();
let mut segments= line.split(' ');
if segments.next().unwrap() == "Fen:" {
let fen = segments.collect::<Vec<&str>>().join(" ");
// Keep reading lines until reached "Checkers", which is in the last line
while !self.read_line().contains("Checkers") {}
return Ok(fen);
}
}
}
/// Plays a move on the current chess position in which Stockfish is playing.
/// This function only updates the board; it does not prompt Stockfish to begin calculating.
///
/// # Example
///
/// ```rust
/// let mut stockfish = Stockfish::new("stockfish.exe")?;
///
/// stockfish.print_board()?;
///
/// stockfish.play_move("e2e4")?;
///
/// // See that the move has been played on the board
/// stockfish.print_board()?;
/// ```
///
/// # Errors
///
/// Returns an [`io::Error`] if an error occurred while trying to
/// communicate with the engine.
pub fn play_move(&mut self, move_str: &str) -> io::Result<()> {
let fen = self.get_fen()?;
let data = format!("position fen {fen} moves {move_str}");
self.uci_send(&data)?;
Ok(())
}
/// Plays a sequence of moves on the current chess position in which Stockfish is playing.
/// This function only updates the board; it does not prompt Stockfish to begin calculating.
///
/// # Example
///
/// ```rust
/// let mut stockfish = Stockfish::new("stockfish.exe")?;
///
/// stockfish.print_board()?;
///
/// let moves = ["e2e4", "e7e5", "f1c4"];
/// stockfish.play_moves(&moves)?;
///
/// // See that the moves have been played on the board
/// stockfish.print_board()?;
/// ```
///
/// # Errors
///
/// Returns an [`io::Error`] if an error occurred while trying to
/// communicate with the engine.
pub fn play_moves(&mut self, moves: &[&str]) -> io::Result<()> {
let fen = self.get_fen()?;
let moves = moves.join(" ");
let data = format!("position fen {fen} moves {moves}");
self.uci_send(&data)?;
Ok(())
}
/// Makes Stockfish calculate to the depth that has been set. (The default
/// depth is 15.)
///
/// Once Stockfish has finished its calculations, this function should return
/// an [`EngineOutput`] describing the result of its calculations.
///
/// # Example
///
/// ```rust
/// let mut stockfish = Stockfish::new("stockfish.exe")?;
///
/// let engine_output = stockfish.go()?;
/// println!("output from stockfish: {engine_output:?}");
/// ```
///
/// # Errors
///
/// Returns an [`io::Error`] if an error occurred while trying to
/// communicate with the engine.
pub fn go(&mut self) -> io::Result<EngineOutput> {
let message = String::from("go depth ") + &self.depth.to_string();
self.uci_send(&message)?;
self.get_engine_output()
}
/// Makes Stockfish calculate for a specified amount of time. Blocks the calling thread
/// for the duration of the specified calculation time.
///
/// Once Stockfish has finished its calculations, this function should return
/// an [`EngineOutput`] describing the result of its calculations.
///
/// # Example
///
/// ```rust
/// use std::time::Duration;
/// let mut stockfish = Stockfish::new("stockfish.exe")?;
///
/// let engine_output = stockfish.go_for(Duration::from_millis(500))?;
/// println!("output from stockfish: {engine_output:?}");
/// ```
///
/// # Errors
///
/// Returns an [`io::Error`] if an error occurred while trying to
/// communicate with the engine.
pub fn go_for(&mut self, calculation_time: Duration) -> io::Result<EngineOutput> {
self.uci_send("go")?;
std::thread::sleep(calculation_time);
self.uci_send("stop")?;
self.get_engine_output()
}
/// Makes Stockfish calculate for a variable time based on the times given as parameters.
/// If for example Stockfish were analyzing from the white side and `white_time` is low
/// (say, only 10 seconds), then Stockfish will use less time for its calculation.
/// The parameters are to be given in milliseconds.
///
/// Once Stockfish has finished its calculations, this function should return
/// an [`EngineOutput`] describing the result of its calculations.
///
/// # Example
///
/// ```rust
/// let mut stockfish = Stockfish::new("stockfish.exe")?;
///
/// let engine_output = stockfish.go_based_on_times(
/// Some(50_000), // White has 50 seconds
/// Some(55_000), // Black has 55 seconds
/// )?;
/// println!("output from stockfish: {engine_output:?}");
/// ```
///
/// # Errors
///
/// Returns an [`io::Error`] if an error occurred while trying to
/// communicate with the engine.
pub fn go_based_on_times(&mut self, white_time: Option<u32>, black_time: Option<u32>) -> io::Result<EngineOutput> {
let mut message = String::from("go");
if let Some(time) = white_time {
message += &format!(" wtime {time}");
}
if let Some(time) = black_time {
message += &format!(" btime {time}");
}
self.uci_send(&message)?;
self.get_engine_output()
}
/// Configures the depth to which Stockfish will calculate. When methods like `go`
/// and `go_for` are called, this field is used to determine how deeply Stockfish will
/// calculate.
///
/// # Example
///
/// ```rust
/// let mut stockfish = Stockfish::new("stockfish.exe")?;
/// stockfish.set_depth(20)?;
/// let engine_output = stockfish.go()?; // Stockfish will calculate to the newly set depth
/// println!("output from stockfish: {engine_output:?}");
/// ```
///
/// # Errors
///
/// Returns an [`io::Error`] if an error occurred while trying to
/// communicate with the engine.
pub fn set_depth(&mut self, depth: u32) {
self.depth = depth;
}
/// This method is meant to only be called after Stockfish has received
/// a command for calculating a position.
/// Reads the lines outputted by the Stockfish process and returns an [`EngineOutput`]
/// value describing Stockfish's evaluation and its chosen best move.
fn get_engine_output(&mut self) -> io::Result<EngineOutput> {
let fen = self.get_fen()?;
// The output from stockfish normally displays the value of the evaluation score
// relative to the player with the current move. Use a multiplier to flip it such that
// the score is not relative to the player with the current move.
let color_multiplier = if fen.contains('w') {1} else {-1};
let mut previous_line: Option<String> = None;
loop {
let line = self.read_line();
let mut segments = line.split(' ');
let first_segment = segments.next()
.expect("should be able to get first segment");
if first_segment != "bestmove" {
previous_line = Some(line);
continue;
}
let previous_line = previous_line.unwrap();
let previous_segments: Vec<&str> = previous_line.split(' ').collect();
let mut score_type = None;
let mut score_value: Option<i32> = None;
let mut depth: Option<u32> = None;
for (i, segment) in previous_segments.iter().enumerate() {
if *segment == "depth" {
depth = Some(
previous_segments[i + 1].parse()
.expect("should be able to parse stockfish info line")
);
} else if *segment == "score" {
score_type = Some(previous_segments[i + 1]);
score_value = Some(
previous_segments[i + 2].parse::<i32>()
.expect("should be able to parse stockfish info line")
* color_multiplier);
}
if depth.is_some() && score_type.is_some() {
break;
}
}
let score_type = score_type.expect("info line should have score type");
let score_value = score_value.expect("info line should have score value");
let depth = depth.expect("info line should have score value");
let score_type = EvalType::from_descriptor(score_type);
let eval = EngineEval::new(score_type, score_value);
let best_move = segments.next()
.expect("should be able to parse stockfish bestmove line")
.to_owned();
let pondered_move = if segments.next().is_some_and(|str| str == "ponder") {
Some(segments.next()
.expect("should be able to parse stockfish ponder entry")
.to_owned())
} else {
None
};
let output = EngineOutput::new(eval, best_move, pondered_move, depth);
return Ok(output);
}
}
/// Returns a string showing a visual display of the current chess position
/// in which Stockfish is playing.
///
/// # Example
///
/// ```rust
/// let mut stockfish = Stockfish::new("stockfish.exe")?;
/// stockfish.play_move("d2d4")?;
///
/// let board = stockfish.get_board_display()?;
/// println!("board: {board}");
/// ```
///
/// # Illustration
/// Example of the output from Stockfish:
///
/// ```
/// +---+---+---+---+---+---+---+---+
/// | r | n | b | q | k | b | n | r | 8
/// +---+---+---+---+---+---+---+---+
/// | p | p | p | p | p | p | p | p | 7
/// +---+---+---+---+---+---+---+---+
/// | | | | | | | | | 6
/// +---+---+---+---+---+---+---+---+
/// | | | | | | | | | 5
/// +---+---+---+---+---+---+---+---+
/// | | | | | | | | | 4
/// +---+---+---+---+---+---+---+---+
/// | | | | | | | | | 3
/// +---+---+---+---+---+---+---+---+
/// | P | P | P | P | P | P | P | P | 2
/// +---+---+---+---+---+---+---+---+
/// | R | N | B | Q | K | B | N | R | 1
/// +---+---+---+---+---+---+---+---+
/// a b c d e f g h
/// ```
///
/// # Errors
///
/// Returns an [`io::Error`] if an error occurred while trying to
/// communicate with the engine.
pub fn get_board_display(&mut self) -> io::Result<String> {
self.uci_send("d")?;
let mut lines: Vec<String> = Vec::with_capacity(20);
loop {
let line = self.read_line();
if line.is_empty() {
continue;
}
let first_segment = line.split(' ').next()
.expect("non-empty line should have segment");
if first_segment == "Fen:" {
break;
}
lines.push(line);
}
Ok(lines.join("\n"))
}
/// This function simply prints the result from `get_board_display`.
///
/// # Example
///
/// ```rust
/// let mut stockfish = Stockfish::new("stockfish.exe")?;
///
/// stockfish.play_move("d2d4")?;
/// stockfish.print_board()?;
///
/// stockfish.play_move("d7d5")?;
/// stockfish.print_board()?;
/// ```
///
/// # Errors
///
/// Returns an [`io::Error`] if an error occurred while trying to
/// communicate with the engine.
pub fn print_board(&mut self) -> io::Result<()> {
let board_display = self.get_board_display()?;
println!("{board_display}");
Ok(())
}
/// Sets a UCI option for the Stockfish engine. This is used for changing the engine's
/// internal parameters.
///
/// # Example
///
/// ```rust
/// let mut stockfish = Stockfish::new("stockfish.exe")?;
/// stockfish.set_option("Move Overhead", "20")?;
/// ```
/// The following is a listing of some of the possible options and their default values.
/// (Note: these may be subject to change, and may not be universal.)
/// - `"Threads"`: 1,
/// - `"Hash"`: 16,
/// - `"Debug Log File"`: "",
/// - `"Contempt"`: 0,
/// - `"Min Split Depth"`: 0,
/// - `"Ponder"`: "false",
/// - `"MultiPV"`: 1,
/// - `"Move Overhead"`: 10,
/// - `"Minimum Thinking Time"`: 20,
/// - `"Slow Mover"`: 100,
/// - `"UCI_Chess960"`: "false",
/// - `"UCI_LimitStrength"`: "false",
/// - `"UCI_Elo"`: 1350,
/// - `"Skill Level"`: 20,
///
/// # Errors
///
/// Returns an [`io::Error`] if an error occurred while trying to
/// communicate with the engine.
pub fn set_option(&mut self, option_name: &str, option_value: &str) -> io::Result<()> {
self.uci_send(&format!("setoption name {option_name} value {option_value}"))
}
/// Sets the size of Stockfish's hashtable/transposition table.
/// Value is given in megabytes. Generally, the larger the table, the
/// faster the engine will run.
///
/// # Example
///
/// ```rust
/// let mut stockfish = Stockfish::new("stockfish.exe")?;
/// stockfish.set_hash(64)?;
/// ```
///
/// # Errors
///
/// Returns an [`io::Error`] if an error occurred while trying to
/// communicate with the engine.
pub fn set_hash(&mut self, hash: u32) -> io::Result<()> {
self.set_option("Hash", &hash.to_string())
}
/// Sets the number of CPU threads that Stockfish will use in its calculations.
/// For Stockfish, it's recommended to set this equal to the number of available
/// CPU cores on your machine.
///
/// # Example
///
/// ```rust
///
/// let mut stockfish = Stockfish::new("stockfish.exe")?;
/// stockfish.set_threads(16)?;
/// ```
///
/// # Errors
///
/// Returns an [`io::Error`] if an error occurred while trying to
/// communicate with the engine.
pub fn set_threads(&mut self, threads: u32) -> io::Result<()> {
self.set_option("Threads", &threads.to_string())
}
/// Sets the elo at which Stockfish will aim to play.
///
/// Similar to `set_skill_level` in functionality, however, calling
/// either one of these two functions will **override** the effect of the other.
///
/// # Example
///
/// ```rust
/// let mut stockfish = Stockfish::new("stockfish.exe")?;
/// stockfish.set_fen_position("r1bqkbnr/ppp1pppp/2np4/8/8/3P4/PPPBPPPP/RN1QKBNR w KQkq - 0 1")?;
///
/// stockfish.set_skill_level(10)?; // The effect of this call is overridden by set_elo
///
/// stockfish.set_elo(1450)?;
///
/// let engine_output = stockfish.go()?;
/// ```
///
/// # Errors
///
/// Returns an [`io::Error`] if an error occurred while trying to
/// communicate with the engine.
pub fn set_elo(&mut self, elo: u32) -> io::Result<()> {
self.set_option("UCI_LimitStrength", "true")?;
self.set_option("Elo", &elo.to_string())
}
/// Sets the skill level at which Stockfish will aim to play. Skill level
/// is given in the range of 0 to 20 (from weakest to strongest.)
///
/// Similar to `set_elo` in functionality, however, calling either one of
/// these two functions will **override** the effect of the other.
///
/// # Example
///
/// ```rust
/// let mut stockfish = Stockfish::new("stockfish.exe")?;
/// stockfish.set_fen_position("r1bqkbnr/ppp1pppp/2np4/8/8/3P4/PPPBPPPP/RN1QKBNR w KQkq - 0 1")?;
///
/// stockfish.set_elo(2500)?; // The effect of this call is overridden by set_skill_level
///
/// stockfish.set_skill_level(16)?;
///
/// let engine_output = stockfish.go()?;
/// ```
///
/// # Errors
///
/// Returns an [`io::Error`] if an error occurred while trying to
/// communicate with the engine.
pub fn set_skill_level(&mut self, skill_level: u32) -> io::Result<()> {
self.set_option("UCI_LimitStrength", "false")?;
self.set_option("Skill Level", &skill_level.to_string())
}
/// Returns a string representing the version of Stockfish being run.
/// Returns [`None`] if the version wasn't able to be parsed from Stockfish's
/// output.
#[must_use]
pub fn get_version(&self) -> &Option<String> {
&self.version
}
/// Sends the `"quit"` UCI command to the Stockfish process, whereupon it
/// will attempt to quit the program as soon as possible.
///
/// # Example
///
/// ```rust
/// let mut stockfish = Stockfish::new("stockfish.exe")?;
/// stockfish.set_fen_position("rn1qkbnr/pbpppppp/1p6/8/8/1P2P3/PBPP1PPP/RN1QKBNR w KQkq - 0 1")?;
/// let engine_output = stockfish.go()?;
///
/// stockfish.quit()?;
/// ```
///
/// # Errors
///
/// Returns an [`io::Error`] if an error occurred while trying to
/// communicate with the engine.
pub fn quit(&mut self) -> io::Result<()> {
self.uci_send("quit")
}
/// Sends a [UCI](https://gist.github.com/DOBRO/2592c6dad754ba67e6dcaec8c90165bf)
/// command to the engine.
///
/// Use carefully; this function itself does not handle or return output
/// that may be incurred by the sent command.
///
/// # Errors
///
/// Returns an [`io::Error`] if an error occurred while trying to
/// communicate with the engine.
pub fn uci_send(&mut self, command: &str) -> io::Result<()> {
self.interactive_process.send(command)?;
Ok(())
}
/* Private Methods */
fn read_line(&mut self) -> String {
self.receiver.recv().expect("should be able to read from receiver")
}
}