ucui 0.1.2

A minimal UCI engine frontend experiment
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
use ratatui::layout::Rect;
use shakmaty::{Chess, Move, Position, Role, Square};
use std::{
    cmp::Ordering,
    collections::{linked_list, LinkedList},
};
use tui_big_text::PixelSize;

#[allow(unused)]
const ALPHA: [char; 26] = [
    'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
    't', 'u', 'v', 'w', 'x', 'y', 'z',
];

const ALPHA_START: u32 = 97;
const ALPHA_END: u32 = 122;

#[allow(unused)]
pub fn i_to_alpha(i: usize) -> String {
    let repeat = (i / 26) + 1;
    let index = i % 26;
    let c = ALPHA[index];
    (0..repeat).map(|_| c).collect()
}

pub fn alpha_to_i(a: &str) -> Result<usize, &str> {
    if let Some(c) = a.chars().next() {
        let repeat = a.len() - 1;
        let u = u32::from(c);
        if (ALPHA_START..=ALPHA_END).contains(&u) {
            let i = (u - ALPHA_START) as usize;
            let r = 26 * repeat + i;
            return Ok(r);
        }
    }
    Err("failed to parse alpha")
}

pub fn san_format_move(pos: &Chess, m: &Move, already_played: bool) -> String {
    use shakmaty::san::San;
    let san_string = San::from_move(pos, m).to_string();
    let played = if already_played {
        Ok(pos.clone())
    } else {
        pos.clone().play(m)
    };
    match played {
        Err(_) => san_string,
        Ok(pos) => {
            if pos.is_checkmate() {
                return format!("{}#", san_string);
            } else if pos.is_check() {
                return format!("{}+", san_string);
            }
            san_string
        }
    }
}

pub struct MoveMap {
    source: Vec<Move>,
    moves: Vec<(Role, usize)>,
}

pub const ROLE_LIST: [Role; 6] = [
    Role::Pawn,
    Role::Bishop,
    Role::Knight,
    Role::Rook,
    Role::Queen,
    Role::King,
];

fn next_role_raw(r: Role) -> Role {
    match r {
        Role::Pawn => Role::Bishop,
        Role::Bishop => Role::Knight,
        Role::Knight => Role::Rook,
        Role::Rook => Role::Queen,
        Role::Queen => Role::King,
        Role::King => Role::Pawn,
    }
}
pub fn next_role(r: Role, map: &MoveMap) -> Option<Role> {
    let mut candidate = r;
    for _i in 0..ROLE_LIST.len() {
        candidate = next_role_raw(candidate);
        if !map.get_line(&candidate).is_empty() {
            return Some(candidate);
        }
    }
    None
}
fn prev_role_raw(r: Role) -> Role {
    match r {
        Role::Pawn => Role::King,
        Role::Bishop => Role::Pawn,
        Role::Knight => Role::Bishop,
        Role::Rook => Role::Knight,
        Role::Queen => Role::Rook,
        Role::King => Role::Queen,
    }
}

pub fn prev_role(r: Role, map: &MoveMap) -> Option<Role> {
    let mut candidate = r;
    for _i in 0..ROLE_LIST.len() {
        candidate = prev_role_raw(candidate);
        if !map.get_line(&candidate).is_empty() {
            return Some(candidate);
        }
    }
    None
}

pub fn next_index(len: usize, i: usize) -> usize {
    if len == 0 || i + 1 >= len {
        0
    } else {
        i + 1
    }
}

pub fn prev_index(len: usize, i: usize) -> usize {
    if len == 0 {
        0
    } else if i == 0 {
        len - 1
    } else {
        i - 1
    }
}

#[derive(Clone, Eq, PartialEq, Debug, Default)]
pub enum MoveIndex {
    #[default]
    None,
    Role(Role),
    Full(Role, usize),
}

fn sort_square(a: Square, b: Square) -> Ordering {
    if a.file() > b.file() {
        Ordering::Greater
    } else if a.file() < b.file() {
        Ordering::Less
    } else if a.rank() > b.rank() {
        Ordering::Greater
    } else if a.rank() < b.rank() {
        Ordering::Less
    } else {
        Ordering::Equal
    }
}

fn sort_move(a: &Move, b: &Move) -> Ordering {
    if a == b {
        Ordering::Equal
    } else {
        match (a, b) {
            (Move::Put { .. }, Move::Put { .. }) => Ordering::Equal,
            (Move::Put { .. }, _) => Ordering::Less,
            (_, Move::Put { .. }) => Ordering::Greater,
            (a, b) => match sort_square(a.from().unwrap(), b.from().unwrap()) {
                Ordering::Equal => sort_square(a.to(), b.to()),
                ord => ord,
            },
        }
    }
}

impl MoveMap {
    pub fn new(mut source: Vec<Move>) -> Self {
        source.sort_by(sort_move);

        let moves: Vec<(Role, usize)> = source
            .iter()
            .enumerate()
            .map(|(i, m)| (m.role(), i))
            .collect();

        Self { source, moves }
    }

    pub fn from_game(game: &Chess) -> Self {
        MoveMap::new(game.legal_moves().iter().map(Move::clone).collect())
    }

    pub fn is_empty(&self) -> bool {
        self.source.is_empty()
    }

    pub fn get_line(&self, role: &Role) -> Vec<(MoveIndex, Move)> {
        let source = &self.source;
        self.moves
            .iter()
            .filter(|(r, _)| *r == *role)
            .enumerate()
            .map(|(line_index, (r, global_index))| {
                (
                    MoveIndex::Full(*r, line_index),
                    source[*global_index].clone(),
                )
            })
            .collect::<Vec<_>>()
    }

    pub fn get_move(&self, role: Role, index: usize) -> Option<Move> {
        let source = &self.source;
        self.moves
            .iter()
            .filter(|(r, _)| *r == role)
            .enumerate()
            .find(|(li, _)| *li == index)
            .map(|(_, (_, i))| source[*i].clone())
    }
}

pub enum PaddingMod {
    Top(u16),
    // Right(u16),
    // Bottom(u16),
    // Left(u16),
}

fn u16add(a: u16, b: u16) -> u16 {
    a.checked_add(b).unwrap_or(u16::MAX)
}

// fn u16min(a: u16, b: u16) -> u16 {
//     a.checked_sub(b).unwrap_or(0)
// }

pub fn shrink_rect(rect: Rect, padding: PaddingMod) -> Rect {
    match padding {
        PaddingMod::Top(n) => Rect {
            y: u16add(rect.y, n),
            ..rect
        },
        // PaddingMod::Right(n) => Rect {
        //     width: u16min(rect.width, n),
        //     ..rect
        // },
        // PaddingMod::Bottom(n) => Rect {
        //     height: u16min(rect.height, n),
        //     ..rect
        // },
        // PaddingMod::Left(n) => Rect {
        //     x: u16add(rect.x, n),
        //     ..rect
        // },
    }
}

// why its not public is beyond me...
// (width , height)
// pub(crate) fn pixels_per_cell(self) -> (u16, u16) {
//     match self {
//         PixelSize::Full => (1, 1),
//         PixelSize::HalfHeight => (1, 2),
//         PixelSize::HalfWidth => (2, 1),
//         PixelSize::Quadrant => (2, 2),
//         PixelSize::ThirdHeight => (1, 3),
//         PixelSize::Sextant => (2, 3),
//     }
// }
pub fn px_height(px: PixelSize) -> u16 {
    match px {
        PixelSize::Full => 8,
        PixelSize::HalfHeight => 8 / 2,
        PixelSize::HalfWidth => 8,
        PixelSize::Quadrant => 8 / 2,
        PixelSize::ThirdHeight => 8 / 3,
        PixelSize::Sextant => 8 / 3,
    }
}
pub fn px_width(px: PixelSize) -> u16 {
    match px {
        PixelSize::Full => 8,
        PixelSize::HalfHeight => 8,
        PixelSize::HalfWidth => 8 / 2,
        PixelSize::Quadrant => 8 / 2,
        PixelSize::ThirdHeight => 8,
        PixelSize::Sextant => 8 / 2,
    }
}

pub fn check_rect(base: Rect, candidate: Rect) -> Rect {
    let x = if candidate.x < base.x {
        base.x
    } else {
        candidate.x
    };
    let y = if candidate.y < base.y {
        base.y
    } else {
        candidate.y
    };
    let width = if x + candidate.width > base.x + base.width {
        base.width.saturating_sub(x)
    } else {
        candidate.width
    };
    let height = if y + candidate.height > base.y + base.height {
        base.height.saturating_sub(y)
    } else {
        candidate.height
    };
    Rect {
        x,
        y,
        width,
        height,
    }
}

pub mod role {
    use crate::ui::{BLACK_BISHOP, BLACK_KING, BLACK_KNIGHT, BLACK_PAWN, BLACK_QUEEN, BLACK_ROOK};
    use shakmaty::Role;

    pub fn role_symbol(role: &Role) -> &'static str {
        match role {
            shakmaty::Role::Pawn => BLACK_PAWN,
            shakmaty::Role::Rook => BLACK_ROOK,
            shakmaty::Role::Knight => BLACK_KNIGHT,
            shakmaty::Role::Bishop => BLACK_BISHOP,
            shakmaty::Role::Queen => BLACK_QUEEN,
            shakmaty::Role::King => BLACK_KING,
        }
    }

    pub fn role_name(role: &Role) -> &'static str {
        match role {
            shakmaty::Role::Pawn => "Pawn",
            shakmaty::Role::Rook => "Rook",
            shakmaty::Role::Knight => "Knight",
            shakmaty::Role::Bishop => "Bishop",
            shakmaty::Role::Queen => "Queen",
            shakmaty::Role::King => "King",
        }
    }
    #[allow(unused)]
    pub fn role_letter(role: &Role) -> &'static str {
        match role {
            shakmaty::Role::Pawn => "P",
            shakmaty::Role::Rook => "R",
            shakmaty::Role::Knight => "N",
            shakmaty::Role::Bishop => "B",
            shakmaty::Role::Queen => "Q",
            shakmaty::Role::King => "K",
        }
    }

    pub enum RoleFormatItem {
        Space,
        Symbol,
        Name,
        String(String),
    }

    pub fn space() -> RoleFormatItem {
        RoleFormatItem::Space
    }
    pub fn name() -> RoleFormatItem {
        RoleFormatItem::Name
    }
    pub fn symbol() -> RoleFormatItem {
        RoleFormatItem::Symbol
    }
    pub fn string<S: Into<String>>(s: S) -> RoleFormatItem {
        RoleFormatItem::String(s.into())
    }

    pub fn format(role: Role, template: &[RoleFormatItem]) -> String {
        template
            .iter()
            .map(|i| match i {
                RoleFormatItem::Space => String::from(" "),
                RoleFormatItem::Name => role_name(&role).to_string(),
                RoleFormatItem::Symbol => role_symbol(&role).to_string(),
                RoleFormatItem::String(s) => s.clone(),
            })
            .collect()
    }
}

#[derive(Clone)]
pub struct RotatingList<T> {
    cap: usize,
    list: LinkedList<T>,
}

impl<T> RotatingList<T> {
    pub fn new(cap: usize) -> Self {
        RotatingList {
            cap,
            list: LinkedList::new(),
        }
    }

    pub fn push(&mut self, elem: T) {
        let len = self.list.len();
        self.list.push_back(elem);
        if len >= self.cap {
            let _ = self.list.pop_front();
        }
    }

    pub fn iter(&self) -> linked_list::Iter<'_, T> {
        self.list.iter()
    }
}

// pub mod recv {
//     use std::{sync::mpsc::channel, thread::spawn};

//     use crossterm::event::Event;

//     use crate::state::StateValue;

//     enum MultiMessage {
//         State(StateValue),
//         Event(Event),
//     }
//     struct Multi {
//         rx: std::sync::mpsc::Receiver<MultiMessage>,
//     }

//     impl Multi {
//         fn new(
//             state: std::sync::mpsc::Receiver<StateValue>,
//             event: std::sync::mpsc::Receiver<Event>,
//         ) -> Self {
//             let (tx, rx) = channel::<MultiMessage>();
//             let tx1 = tx.clone();
//             spawn(move || loop {
//                 match state.recv() {
//                     Err(_) => break,
//                     Ok(m) => {
//                         let _ = tx1.send(MultiMessage::State(m));
//                     }
//                 }
//             });
//             let tx2 = tx.clone();
//             spawn(move || loop {
//                 match event.recv() {
//                     Err(_) => break,
//                     Ok(m) => {
//                         let _ = tx2.send(MultiMessage::Event(m));
//                     }
//                 }
//             });

//             Self { rx }
//         }

//         fn start(&self, tx: std::sync::mpsc::Sender<MultiMessage>) {
//             loop {
//                 match self.rx.recv() {
//                     Ok(m) => {
//                         let _ = tx.send(m);
//                     }
//                     Err(_) => break,
//                 }
//             }
//         }
//     }

//     pub fn multi(
//         state: std::sync::mpsc::Receiver<StateValue>,
//         event: std::sync::mpsc::Receiver<Event>,
//     ) -> std::sync::mpsc::Receiver<MultiMessage> {
//         let multi = Multi::new(state, event);
//         let (tx, rx) = channel::<MultiMessage>();

//         spawn(move || {
//             multi.start(tx);
//         });

//         rx
//     }
// }

#[cfg(test)]
mod tests {
    use super::*;
    use shakmaty::{Chess, Move};
    use shakmaty_uci::UciMove;

    fn mov(s: &str, game: &Chess) -> Move {
        s.parse::<UciMove>().expect(s).to_move(game).expect("legal")
    }

    #[test]
    fn check_ordering() {
        let mut game = Chess::default();

        game.play_unchecked(&mov("e2e4", &game));
        game.play_unchecked(&mov("e7e6", &game));

        let sorted = MoveMap::from_game(&game).get_line(&Role::Pawn);
        for (i, (_, m)) in sorted.iter().enumerate() {
            println!("{} -> {}{}", i, m.from().unwrap(), m.to());
        }

        let rm = mov("e4e5", &game);
        let at8 = sorted[8].clone().1;
        assert_eq!(at8, rm);
    }
}