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
use super::*;
use crate::game::GameView;

use cursive::direction::Direction;
use cursive::event::{Event, EventResult, Key};
use cursive::theme;
use cursive::theme::ColorStyle;
use cursive::Printer;
use cursive::Vec2;

#[derive(Hash, Eq, PartialEq, Copy, Clone, Debug)]
enum PendingMove {
    SelectingPosition(usize, usize),
    SelectingMove(Move),
}

/// Interactive interface for Breakthrough
pub struct IBreakthrough {
    game: Breakthrough,
    choosing_move: Option<PendingMove>,
    choosing_move_cb: Option<Box<dyn FnOnce(Move, &mut IBreakthrough) + Send + Sync>>,
}

impl IBreakthrough {
    /// Instanciates a view with given state.
    pub fn new(initial_state: Breakthrough) -> Self {
        IBreakthrough {
            game: initial_state,
            choosing_move: None,
            choosing_move_cb: None,
        }
    }

    fn handle_move(&mut self, dx: isize, dy: isize) -> EventResult {
        if let Some(m) = &self.choosing_move {
            match m {
                PendingMove::SelectingPosition(x, y) => {
                    let x = *x;
                    let y = *y;
                    let possible_moves = self.game.possible_moves();
                    let new_m = possible_moves
                        .iter()
                        .filter(|m| {
                            (dx != 0 && (m.x as isize - x as isize) * dx > 0)
                                || (dy != 0 && (m.y as isize - y as isize) * dy > 0)
                        })
                        .min_by_key(|m| {
                            let a = m.x as isize - x as isize;
                            let b = m.y as isize - y as isize;
                            if dx == 0 {
                                (b * dy, a.abs())
                            } else {
                                (a * dx, b.abs())
                            }
                        });
                    if let Some(new_m) = new_m {
                        self.choosing_move = Some(PendingMove::SelectingPosition(new_m.x, new_m.y))
                    }
                }
                PendingMove::SelectingMove(m) => {
                    if dx == 0 {
                        self.choosing_move = Some(PendingMove::SelectingPosition(m.x, m.y))
                    } else {
                        let new_m = MoveDirection::all()
                            .iter()
                            .map(|d| Move {
                                color: self.game.turn(),
                                direction: *d,
                                x: m.x,
                                y: m.y,
                            })
                            .filter(|m| m.is_valid(self.game.content.view()).is_some())
                            .filter(|m2| {
                                let m2_t = m2.target();
                                let m_t = m.target();
                                (m2_t.0 as isize - m_t.0 as isize) * dx > 0
                            })
                            .min_by_key(|m2| {
                                let m2_t = m2.target();
                                let m_t = m.target();
                                (m2_t.0 as isize - m_t.0 as isize) * dx
                            });
                        if let Some(new_m) = new_m {
                            self.choosing_move = Some(PendingMove::SelectingMove(new_m))
                        }
                    }
                }
            };
            EventResult::Consumed(None)
        } else {
            EventResult::Ignored
        }
    }
}

impl cursive::view::View for IBreakthrough {
    fn draw(&self, printer: &Printer) {
        let black_color = ColorStyle::new(
            theme::Color::RgbLowRes(0, 0, 0),
            theme::Color::TerminalDefault,
        );

        let white_color = ColorStyle::new(
            theme::Color::RgbLowRes(5, 3, 5),
            theme::Color::TerminalDefault,
        );
        // print letters
        for x in 0..self.game.K {
            printer.print(
                (2 + 3 * x, 0),
                &(('a' as usize + x) as u8 as char).to_string(),
            );
            printer.print((0, 2 + 2 * x), &format!("{}", 1 + x));
        }
        printer.print((1, 1), &format!("╔{}══╗", "══╤".repeat(self.game.K - 1)));
        for y in 0..self.game.K {
            if y != 0 {
                printer.print(
                    (1, 1 + 2 * y),
                    &format!("╟{}──╢", "──┼".repeat(self.game.K - 1)),
                );
            }
            printer.print((1, 2 + 2 * y), "║");
            for x in 0..self.game.K {
                if x != 0 {
                    printer.print((1 + 3 * x, 2 + 2 * y), "│")
                };

                match self.game.content[[x, y]] {
                    Cell::Empty => (),
                    Cell::C(Color::Black) => printer.with_color(black_color, |printer| {
                        printer.print((2 + 3 * x, 2 + 2 * y), "▓▓")
                    }),
                    Cell::C(Color::White) => printer.with_color(white_color, |printer| {
                        printer.print((2 + 3 * x, 2 + 2 * y), "▓▓")
                    }),
                }
            }
            printer.print((1 + 3 * self.game.K, 2 + 2 * y), "║");
        }
        printer.print(
            (1, 1 + 2 * self.game.K),
            &format!("╚{}══╝", "══╧".repeat(self.game.K - 1)),
        );

        let select_color = ColorStyle::new(
            theme::Color::RgbLowRes(1, 1, 1),
            theme::Color::RgbLowRes(4, 4, 4),
        );

        if let Some(m) = self.choosing_move {
            let (x, y) = match m {
                PendingMove::SelectingPosition(x, y) => (x, y),
                PendingMove::SelectingMove(m) => (m.x, m.y),
            };
            printer.with_color(select_color, |printer| {
                printer.print((1 + 3 * x, 1 + 2 * y), "┏━━┓");
                printer.print((1 + 3 * x, 2 + 2 * y), "┣");
                printer.print((4 + 3 * x, 2 + 2 * y), "┫");
                printer.print((1 + 3 * x, 3 + 2 * y), "┗━━┛");
            });

            if let PendingMove::SelectingMove(mv) = m {
                for direction in &[
                    MoveDirection::Front,
                    MoveDirection::FrontLeft,
                    MoveDirection::FrontRight,
                ] {
                    let m = Move {
                        color: self.game.turn(),
                        x,
                        y,
                        direction: *direction,
                    };
                    match m.is_valid(self.game.content.view()) {
                        None => (),
                        Some((px, py)) => {
                            let (px, py, color) = if *direction == mv.direction {
                                (
                                    px,
                                    py,
                                    ColorStyle::new(
                                        theme::Color::RgbLowRes(5, 0, 0),
                                        theme::Color::RgbLowRes(4, 4, 4),
                                    ),
                                )
                            } else {
                                (
                                    px,
                                    py,
                                    ColorStyle::new(
                                        theme::Color::RgbLowRes(0, 0, 0),
                                        theme::Color::RgbLowRes(4, 4, 4),
                                    ),
                                )
                            };
                            printer.with_color(color, |printer| {
                                printer.print((1 + 3 * px, 1 + 2 * py), "┼──┼");
                                printer.print((1 + 3 * px, 2 + 2 * py), "│▒▒│");
                                printer.print((1 + 3 * px, 3 + 2 * py), "┼──┼");
                            });
                        }
                    };
                }
            }
        }
    }

    fn take_focus(&mut self, _: Direction) -> bool {
        true
    }

    fn on_event(&mut self, event: Event) -> EventResult {
        match event {
            Event::Key(Key::Right) => self.handle_move(1, 0),
            Event::Key(Key::Left) => self.handle_move(-1, 0),
            Event::Key(Key::Up) => self.handle_move(0, -1),
            Event::Key(Key::Down) => self.handle_move(0, 1),
            Event::Key(Key::Enter) => {
                if let Some(m) = self.choosing_move {
                    match m {
                        PendingMove::SelectingMove(m) => {
                            if let Some(f) = self.choosing_move_cb.take() {
                                f(m, self);
                            }
                            self.choosing_move = None;
                            EventResult::Consumed(None)
                        }
                        PendingMove::SelectingPosition(x, y) => {
                            self.choosing_move = Some(PendingMove::SelectingMove(
                                *self
                                    .game
                                    .possible_moves()
                                    .iter()
                                    .find(|m| m.x == x && m.y == y)
                                    .unwrap(),
                            ));
                            EventResult::Consumed(None)
                        }
                    }
                } else {
                    EventResult::Ignored
                }
            }
            _ => EventResult::Ignored,
        }
    }

    fn required_size(&mut self, _: Vec2) -> Vec2 {
        Vec2 {
            x: self.game.K * 3 + 3,
            y: self.game.K * 2 + 3,
        }
    }
}

impl GameView for IBreakthrough {
    type G = Breakthrough;

    fn set_state(&mut self, state: Self::G) {
        self.game = state;
    }

    /*
    fn choose_move(&mut self, cb: Box<dyn FnOnce(<Self::G as Base>::Move, &mut Self)>) {
        let possible_moves = self.game.possible_moves();
        let first_move = possible_moves.first().expect("Not possible moves ?");
        self.choosing_move = Some(PendingMove::SelectingPosition(first_move.x, first_move.y));
        self.choosing_move_cb = Some(cb)
    }*/
}