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
use std::time::Duration;
use rand::seq::SliceRandom;
use tokio::sync::oneshot;
use crate::game::pieces::Color;
use crate::game::position::Position;
use crate::game::{Board, Move, Promotion};
#[derive(Debug, Clone, Copy)]
pub struct Brain {
pub color: Color,
board: Board,
pub last_move: Option<Move>,
pub opponent_last_move: Option<Move>,
}
impl Brain {
pub fn new(board: Board, color: Color) -> Self {
Self {
board,
color,
last_move: None,
opponent_last_move: None,
}
}
pub fn opponent_move(&mut self, m: Move) {
self.board.apply_move(m);
self.opponent_last_move = Some(m);
}
pub fn own_move(&mut self, m: Move) {
self.board.apply_move(m);
self.last_move = Some(m);
}
pub fn choose_move(&mut self, sensor: oneshot::Sender<Option<Move>>) {
let color = self.color;
let board = self.board;
rayon::spawn(move || {
std::thread::sleep(Duration::from_secs(1));
let mut m = None;
if let Some(destination) = board
.get_squares_attacked_by_pawns(color)
.into_iter()
.next()
{
let mut board_swap = board.clone();
board_swap.mutate(|board| {
let side = board.get_side_mut(color.opposite());
side.mutate(|side| {
(*side).pawns |= side.rooks;
(*side).pawns |= side.knights;
(*side).pawns |= side.bishops;
(*side).pawns |= side.queens;
});
});
let origin = board_swap
.get_squares_attacked_by_pawns(color.opposite())
.next()
.expect("inconsistency while trying to get attacking pawn");
m = Some(Move(origin, destination, choose_promotion(destination)))
} else {
let pawns = board.get_pawns(color);
if let Some(pawn) = pawns.choose(&mut rand::thread_rng()) {
let origin = pawn.get_position();
let destination = origin.forwards(color, 1);
m = Some(Move(origin, destination, choose_promotion(destination)));
}
}
sensor.send(m).expect("Failed to dispatch Brain move");
})
}
}
fn choose_promotion(destination: Position) -> Promotion {
if destination.rank_y == 0 || destination.rank_y == 7 {
Promotion::Queen
} else {
Promotion::None
}
}