-
Notifications
You must be signed in to change notification settings - Fork 0
/
rec.rs
274 lines (255 loc) · 8.52 KB
/
rec.rs
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
use std::{
slice, fmt
};
use crate::{
Coord,
CoordState,
Rotation,
Error
};
/// Trait for all types that store `Coord<SZ>` sequence in continuous memory
/// and don't allow any coordinate value (except null) to be repeated.
/// Any even index corresponds to a black stone, odd index means it is white.
///
/// Some wrapper (like `GameRec`) can be created in the future, for storing
/// extra informations and ensuring some rules to be followed.
pub trait Rec<const SZ: usize> {
/// Returns a slice of all added coordinates.
fn as_slice(&self) -> &[Coord<SZ>];
/// Returns the state at a coordinate, or `CoordState::Empty` if `coord` is null.
fn coord_state(&self, coord: Coord<SZ>) -> CoordState;
/// Returns the state at a coordinate, causes UB if `coord` is null.
unsafe fn coord_state_unchecked(&self, coord: Coord<SZ>) -> CoordState;
/// Count of all added coordinates.
fn len(&self) -> usize;
/// Possible maximum amount of coordinates (including null).
fn len_max() -> usize;
/// Count of all non-null coordinate.
fn stones_count(&self) -> usize;
/// Returns `false` if `len_max` isn't reached and the board isn't full.
fn is_full(&self) -> bool;
/// Adds a coordinate into the sequence. Returns `Error::CoordNotEmpty`
/// if the coordinate exists in the stored sequence. Other rules can be defined.
fn add(&mut self, coord: Coord<SZ>) -> Result<(), Error>;
/// Undo the last move (removes the last coordinate). Returns `Error::RecIsEmpty`
/// if there is no move. Other rules can be defined.
fn undo(&mut self) -> Result<Coord<SZ>, Error>;
/// Clears the record.
fn clear(&mut self);
/// Returns an iterator of all added coordinates (from first to last).
#[inline(always)]
fn iter(&self) -> slice::Iter<'_, Coord<SZ>> {
self.as_slice().iter()
}
/// Checks if the record is empty.
#[inline(always)]
fn is_empty(&self) -> bool {
self.len() == 0
}
/// Returns the last coordinate (move), or `None` if the record is empty.
#[inline(always)]
fn last_coord(&self) -> Option<Coord<SZ>> {
if ! self.is_empty() {
// SAFETY: assumes self.len is valid
Some(* unsafe { self.as_slice().get_unchecked(self.len() - 1) })
} else {
None
}
}
/// Returns the stone color of the next coordinate (move) to be added.
/// It does not check if the record is full.
#[inline(always)]
fn color_next(&self) -> CoordState {
if self.len() % 2 == 0 {
CoordState::Black
} else {
CoordState::White
}
}
/// Tries to append all coordinates got from iterator `coords`
/// into the current record, stops at the first failure of `add()`.
/// Always return the count of added coordinates.
#[inline]
fn append(&mut self, coords: impl Iterator<Item = Coord<SZ>>) -> Result<usize, usize> {
let mut i: usize = 0;
for c in coords {
if ! self.add(c).is_ok() { return Err(i); }
i += 1;
}
Ok(i)
}
/// Tries to append all coordinates parsed from `str_coords`
/// into the current record, stops at the first failure of `add()`.
/// Always return the count of added coordinates.
fn append_str(&mut self, str_coords: &str) -> Result<usize, usize> {
let mut len_checked = 0;
let mut cnt_added = 0;
while let Some((c, l)) = Coord::<SZ>::parse_str(&str_coords[len_checked..]) {
self.add(c).map_err(|_| cnt_added)?;
cnt_added += 1;
len_checked += l;
}
if cnt_added > 0 {
Ok(cnt_added)
} else {
Err(0)
}
}
/// Finds `coord` in the sequence reversely, returns the count of
/// removed coordinates after `coord` if it's found, otherwise
/// returns `Error::ItemNotExist`.
#[inline]
fn back_to(&mut self, coord: Coord<SZ>) -> Result<usize, Error> {
if let Some(i) = self.iter().rposition(|&c| c == coord) {
let steps = (self.len() - 1) - i;
for _ in 0..steps {
let _ = self.undo();
}
Ok(steps)
} else {
Err(Error::ItemNotExist)
}
}
/// Rotates the board by `rotation`, changes all valid coordinates.
#[inline(always)]
fn rotate(&mut self, rotation: Rotation) {
self.transform(|c| c.rotate(rotation))
}
/// Translates all stones by `x` and `y` offsets, changes all valid coordinates.
/// Returns `Error::TransformFailed` if some stones are out of range after translation,
/// in this case the original record should be kept.
#[inline(always)]
fn translate(&mut self, x: i8, y: i8) -> Result<(), Error> {
self.transform_checked(|c| c.offset(x, y))
}
/// Changes values of all valid coordinates by `f` and refreshes the board.
/// Do make sure `f` is one-to-one mapping and the returned value is always valid,
/// otherwise it may generate an unknown result.
fn transform(&mut self, f: impl Fn(Coord<SZ>) -> Coord<SZ>) {
// Note: Vec is used
let seq = self.iter().map(
|&c| if c.is_real() { f(c) } else { c }
).collect::<Vec<_>>();
self.clear();
for c in seq {
let _ = self.add(c);
}
}
/// Changes values of all valid coordinates by `f` and refreshes the board.
/// Returns `Error::TransformFailed` if failed, in such case the record sequence
/// becomes dirty (has an unknown length).
fn transform_checked<F>(&mut self, f: F) -> Result<(), Error>
where F: Fn(Coord<SZ>) -> Option<Coord<SZ>>
{
let seq = self.iter().map(
|&c| if c.is_real() { f(c) } else { Some(c) }
).collect::<Vec<_>>();
for c in &seq {
if c.is_none() {
return Err(Error::TransformFailed);
}
}
self.clear();
for c in seq {
self.add(c.unwrap())
.map_err(|_| Error::TransformFailed)?;
}
Ok(())
}
/// Prints the current record (for example, to a `String`) in a readable format.
/// It might be overrided if the format does not meet the requirement.
///
/// ```
/// use figrid_board::{ Rec, BaseRec15 };
/// let rec: BaseRec15 = "l10j7k6m11m13".parse().unwrap();
/// let mut s = String::new();
/// rec.print_str(&mut s, ", ", false);
/// assert_eq!(s, "l10, j7, k6, m11, m13");
/// s.clear(); rec.print_str(&mut s, ",", true);
/// assert_eq!(s, "1. l10,j7 2. k6,m11 3. m13");
/// ```
fn print_str(&self, f: &mut impl fmt::Write, divider: &str, print_no: bool) -> std::fmt::Result {
if self.is_empty() { return Ok(()); }
if print_no {
for (i, c) in self.iter().enumerate() {
if i % 2 == 0 {
let div = if i < self.len() - 1 {divider} else {""};
write!(f, "{}. {}{}", i / 2 + 1, c, div)?;
} else {
write!(f, "{} ", c)?;
}
}
} else {
for c in self.iter().take(self.len() - 1) {
write!(f, "{}{}", c, divider)?;
}
write!(f, "{}", self.last_coord().unwrap())?;
}
Ok(())
}
/// Draws the board by characters. `dots` gives extra information to be shown on the board,
/// set to `&[]` if not needed; set `full_char` to `true` if non-ASCII output is possible
/// (and ambiguous width characters should be fullwidth).
fn print_board(&self, f: &mut impl fmt::Write, dots: &[Coord<SZ>], full_char: bool)
-> std::fmt::Result
{
#[allow(non_snake_case)] let SIZE: u8 = SZ as u8;
let ( //actually string literals, not chars
ch_black, ch_black_last, ch_white, ch_white_last, ch_emp, ch_dot,
ch_b, ch_u, ch_l, ch_r, ch_bl, ch_br, ch_ul, ch_ur
) = if full_char {
("●", "◆", "○", "⊙", "┼", "·",
"┴", "┬", "├", "┤", "└", "┘", "┌", "┐")
} else {
(" X", " #", " O", " Q", " .", " *",
" .", " .", " .", " .", " .", " .", " .", " .")
};
for y in (0..SIZE).rev() {
write!(f, " {:2}", y + 1)?;
for x in 0..SIZE {
let coord = Coord::from(x, y);
let st = unsafe {
// SAFETY: ranges of x and y is correct
self.coord_state_unchecked(coord)
};
let ch = match st {
CoordState::Empty => {
if dots.iter().find(|&&c| coord == c)
.is_some() { ch_dot }
else if x == 0 && y == 0 { ch_bl }
else if x == SIZE - 1 && y == 0 { ch_br }
else if x == 0 && y == SIZE - 1 { ch_ul }
else if x == SIZE - 1 && y == SIZE - 1 { ch_ur }
else if x == 0 { ch_l }
else if x == SIZE - 1 { ch_r }
else if y == 0 { ch_b }
else if y == SIZE - 1 { ch_u }
else { ch_emp }
},
CoordState::Black => {
if coord != self.last_coord().unwrap_or(Coord::new()) {
ch_black
} else {
ch_black_last
}
},
CoordState::White => {
if coord != self.last_coord().unwrap_or(Coord::new()) {
ch_white
} else {
ch_white_last
}
}
};
write!(f, "{ch}")?;
}
write!(f, "\n")?;
}
write!(f, " ")?;
for h in 0..SIZE {
write!(f, "{} ", crate::coord_x_letter(h))?;
}
write!(f, "\n")?;
Ok(())
}
}