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
use std::str::FromStr;
use crate::{Board, ChessMove, Color, Square};
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum GameAction {
OfferDraw(Color),
AcceptDraw,
RefuseDraw,
Resign(Color),
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum GameState {
Ongoing,
Checkmates(Color),
Stalemate,
DrawByRequest,
Resigns(Color),
}
impl GameState {
pub fn winner(&self) -> Option<Color> {
match *self {
GameState::Ongoing => None,
GameState::Checkmates(color) => Some(!color),
GameState::Stalemate => None,
GameState::DrawByRequest => None,
GameState::Resigns(color) => Some(!color),
}
}
}
#[derive(Clone, Eq, PartialEq, Default, Debug)]
pub struct Chess {
pub(crate) board: Board,
pub(crate) square_focused: Option<Square>,
pub(crate) history: Vec<String>,
}
impl Chess {
pub fn new(board: Board) -> Self {
Chess {
board,
square_focused: Default::default(),
history: Default::default(),
}
}
pub fn history(&self) -> Vec<String> {
self.history.clone()
}
pub fn undo(&mut self) {
if let Some(fen) = self.history.pop() {
self.board = Board::from_str(fen.as_str()).expect("valid fen from history");
}
}
pub fn reset(&mut self) {
self.board = Board::default();
self.square_focused = None;
self.history = vec![];
}
pub fn state(&self) -> GameState {
let state = self.board.state();
state
}
pub fn play(&mut self, from: Square, to: Square) {
let m = ChessMove::new(from, to);
if self.board.is_legal(m) {
self.history.push(self.board.to_string());
self.board.update(m);
}
self.square_focused = None;
}
}