aboutsummaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 53a72ea1bab1951e67fefd883704fbf213465382 (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
use std::{f32::INFINITY, time::{Duration, Instant}};
use std::env;

use chessnost::board::{Board, Color};

fn opponent_move(board: &mut Board) {
    let mov = match board.read_move() {
        Ok(m) => m,
        Err(e) => {
            println!("Error: {}", e);
            return opponent_move(board);
        }
    };
    print!("{:?}", mov);
    board.make_move(mov);
    board.print();
}

fn computer_move(board: &mut Board, time_left: &mut Duration) {
    let allowed_move_duration = *time_left / 20;
    let max_depth = 6 + (board.ply as i32 / 15) as u8;
    println!("~{:?} left, allocating {:?} for a move", time_left, allowed_move_duration);

    let move_start = Instant::now();
    let (score, pv) = board.iterative_deepening(max_depth, allowed_move_duration);
    let elapsed = move_start.elapsed();

    if *time_left >= elapsed {
        *time_left -= elapsed;
    } else {
        println!("You are probably out of time. I will keep going anyway...");
    }

    println!("Finished in {:?}: score={:?}", elapsed, score);

    let mov = pv[0];
    println!("{:?}", mov);
    board.make_move(mov);
    board.print();
}

fn main() {
    let args: Vec<String> = env::args().collect();
    assert!(args.len() >= 4, "Provide all arguments [COLOR] [TIME_MINUTES] [INCREMENT_SECONDS]");

    let color = match args[1].as_str() {
        "w" => Color::White,
        "b" => Color::Black,
        _ => panic!("Please provide a color [w|b]")
    };

    let mut time_left = Duration::from_secs(60 * match args[2].parse() {
        Ok(x) => x,
        Err(..) => 15
    });

    let increment = Duration::from_secs(match args[3].parse() {
        Ok(x) => x,
        Err(..) => 10
    });
    let manual_decrement = Duration::from_secs(7); // Time to sync moves with the game

    let mut board = if args.len() == 5 {
        Board::from_FEN(args[4].to_string())
    } else {
        Board::new()
    };

    board.print();
    loop {
        time_left += increment;
        time_left -= manual_decrement;

        match color {
            Color::White => {
                computer_move(&mut board, &mut time_left);
                opponent_move(&mut board);
            }
            Color::Black => {
                opponent_move(&mut board);
                computer_move(&mut board, &mut time_left);
            }
        }
    }
}