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
use crate::Algorithm;
use crate::Game;
use crate::Move;
use std::fmt;

#[cfg(test)]
mod tests;

#[derive(Debug, PartialEq, Eq, Clone, Copy, Default)]
pub struct Position(usize);

impl Position {
    fn pos_ne(self) -> Position {
        Position(self.0 + 11)
    }
    fn pos_nw(self) -> Position {
        Position(self.0 + 9)
    }
    fn pos_se(self) -> Position {
        Position(self.0 - 9)
    }
    fn pos_sw(self) -> Position {
        Position(self.0 - 11)
    }

    pub fn new(y: usize, x: usize) -> Position {
        Position(y * 10 + x)
    }

    fn get_y(self) -> usize {
        self.0 / 10
    }

    fn get_x(self) -> usize {
        self.0 % 10
    }
}

#[derive(Debug, PartialEq, Eq, Clone, Copy, Default)]
pub struct FHMove {
    idx: usize,
    dst: usize,
}

impl FHMove {
    fn new_f(dst: Position) -> FHMove {
        FHMove { idx: 4, dst: dst.0 }
    }

    fn new_h(idx: usize, dst: Position) -> FHMove {
        FHMove { idx, dst: dst.0 }
    }

    fn get_idx(&self) -> usize {
        self.idx
    }

    fn get_dst(&self) -> Position {
        Position(self.dst)
    }
}

impl Move for FHMove {
    fn to_str(&self) -> String {
        match self.idx {
            4 => format!("Fox to position {}", self.dst),
            n => format!("Hound {} to position {}", n + 1, self.dst),
        }
    }
}

pub struct FoxAndHounds {
    free_squares: [bool; 100],
    move_no: i32,
    is_fox_next: bool,
    fox_pos: Position,
    hounds_pos: [Position; 4],
    pub draw_with_colors: bool,
}

impl fmt::Debug for FoxAndHounds {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        writeln!(f, "    +---+---+---+---+---+---+---+---+")?;
        for y in (1..9).rev() {
            write!(f, " {}0 | ", y)?;
            for x in 1..9 {
                let pos = Position::new(y, x);
                if self.fox_pos == pos {
                    if self.draw_with_colors {
                        write!(f, "\x1B[31;8mF\x1B[0m")?;
                    } else {
                        write!(f, "F")?;
                    }
                } else if self.hounds_pos[0] == pos
                    || self.hounds_pos[1] == pos
                    || self.hounds_pos[2] == pos
                    || self.hounds_pos[3] == pos
                {
                    if self.draw_with_colors {
                        write!(f, "\x1B[33;8mH\x1B[0m")?;
                    } else {
                        write!(f, "H")?;
                    }
                } else {
                    write!(f, " ")?;
                }
                write!(f, " | ")?;
            }
            writeln!(f, "\n    +---+---+---+---+---+---+---+---+")?;
        }
        writeln!(f, "      1   2   3   4   5   6   7   8  ")?;
        Ok(())
    }
}

#[derive(PartialEq, Eq)]
pub enum StartingPiece {
    Fox,
    Hounds,
}

impl Clone for FoxAndHounds {
    fn clone(&self) -> Self {
        FoxAndHounds {
            move_no: self.move_no,
            is_fox_next: self.is_fox_next,
            fox_pos: self.fox_pos,
            hounds_pos: self.hounds_pos,
            free_squares: self.free_squares,
            draw_with_colors: self.draw_with_colors,
        }
    }
}

impl Game for FoxAndHounds {
    type Move = FHMove;

    fn possible_moves(&self) -> Vec<FHMove> {
        if self.fox_pos.0 >= 80 {
            return vec![]; // game over; fox won
        }

        let mut result = Vec::<FHMove>::with_capacity(8);

        // fox can move in all four directions, hounds can only move downwards
        if self.is_fox_next {
            if self.free_squares[self.fox_pos.0 + 11] {
                result.push(FHMove::new_f(Position(self.fox_pos.0 + 11)));
            }
            if self.free_squares[self.fox_pos.0 + 9] {
                result.push(FHMove::new_f(Position(self.fox_pos.0 + 9)));
            }
            if self.free_squares[self.fox_pos.0 - 9] {
                result.push(FHMove::new_f(Position(self.fox_pos.0 - 9)));
            }
            if self.free_squares[self.fox_pos.0 - 11] {
                result.push(FHMove::new_f(Position(self.fox_pos.0 - 11)));
            }
        } else {
            for i in 0..4 {
                let hound = self.hounds_pos[i].0;
                if self.free_squares[(hound - 9) as usize] {
                    result.push(FHMove::new_h(i, Position(hound - 9)));
                }
                if self.free_squares[(hound - 11) as usize] {
                    result.push(FHMove::new_h(i, Position(hound - 11)));
                }
            }
            // sort with highest hound first since that's more likely to lead
            // to a good move
            result.sort_by_key(|m| 100 - m.get_dst().0);
        }
        result
    }

    fn execute_move(&self, mov: FHMove) -> Self {
        if self.is_fox_next {
            self.check_fox_move(&mov);
        } else {
            self.check_hounds_move(&mov);
        }
        let mut res = self.clone();
        res.do_move(mov);
        res
    }

    fn do_move(&mut self, mov: FHMove) -> FHMove {
        let res;
        if self.is_fox_next {
            res = FHMove::new_f(Position(self.fox_pos.0));
            self.free_squares[self.fox_pos.0] = true;
            self.fox_pos = mov.get_dst();
            self.free_squares[self.fox_pos.0] = false;
        } else {
            let src = self.hounds_pos[mov.get_idx()];
            res = FHMove::new_h(mov.get_idx(), src);
            self.free_squares[src.0] = true;
            self.hounds_pos[mov.get_idx()] = mov.get_dst();
            self.free_squares[mov.get_dst().0] = false;
        }
        self.is_fox_next = !self.is_fox_next;
        self.move_no += 1;
        res
    }

    fn undo_move(&mut self, mov: FHMove) {
        self.is_fox_next = !self.is_fox_next;
        self.move_no -= 1;
        if self.is_fox_next {
            self.free_squares[self.fox_pos.0] = true;
            self.fox_pos = mov.get_dst();
            self.free_squares[self.fox_pos.0] = false;
        } else {
            let src = self.hounds_pos[mov.get_idx()];
            self.free_squares[src.0] = true;
            self.hounds_pos[mov.get_idx()] = mov.get_dst();
            self.free_squares[mov.get_dst().0] = false;
        }
    }

    fn get_score(&self) -> i32 {
        if self.is_game_over() {
            return self.move_no - Self::SCORE_MAX;
        }

        let fox_y = self.fox_pos.get_y();

        if fox_y >= self.hounds_pos[0].get_y()
            && fox_y >= self.hounds_pos[1].get_y()
            && fox_y >= self.hounds_pos[2].get_y()
            && fox_y >= self.hounds_pos[3].get_y()
        {
            if self.is_fox_next {
                Self::SCORE_MAX - self.move_no
            } else {
                self.move_no - Self::SCORE_MAX
            }
        } else if self.is_fox_next {
            fox_y as i32
        } else {
            -(fox_y as i32)
        }
    }

    fn score_if_win_next_round(&self) -> i32 {
        self.move_no + 1 - Self::SCORE_MAX
    }

    fn is_game_over(&self) -> bool {
        if self.fox_pos.0 >= 80 {
            return true;
        }

        // fox can move in all four directions, hounds can only move downwards
        if self.is_fox_next {
            if self.free_squares[(self.fox_pos.0 + 11) as usize] {
                return false;
            }
            if self.free_squares[(self.fox_pos.0 + 9) as usize] {
                return false;
            }
            if self.free_squares[(self.fox_pos.0 - 9) as usize] {
                return false;
            }
            if self.free_squares[(self.fox_pos.0 - 11) as usize] {
                return false;
            }
        } else {
            for i in 0..4 {
                let hound = self.hounds_pos[i];
                if self.free_squares[(hound.0 - 9) as usize] {
                    return false;
                }
                if self.free_squares[(hound.0 - 11) as usize] {
                    return false;
                }
            }
        }
        true
    }

    fn calculate_move<T: Algorithm>(
        &self,
        depth: i32,
        do_precalculated_moves: bool,
    ) -> Option<FHMove> {
        let mut mov = None;
        if do_precalculated_moves {
            mov = match self.move_no {
                0 => Some(FHMove { idx: 4, dst: 24 }),
                2 => Some(FHMove { idx: 4, dst: 35 }),
                4 => Some(FHMove { idx: 4, dst: 44 }),
                6 => Some(FHMove { idx: 4, dst: 53 }),
                8 => Some(FHMove { idx: 4, dst: 64 }),
                1 => Some(FHMove { idx: 3, dst: 77 }),
                3 => Some(FHMove { idx: 2, dst: 75 }),
                5 => Some(FHMove { idx: 1, dst: 73 }),
                7 => Some(FHMove { idx: 0, dst: 71 }),
                _ => None,
            };
            if let Some(m) = mov {
                if !self.possible_moves().contains(&m) {
                    mov = None
                }
            }
        }
        if mov.is_none() {
            mov = T::compute(self, depth);
        }
        mov
    }
}

impl FoxAndHounds {
    pub fn new_fox_starts(fox_starts: bool) -> FoxAndHounds {
        let mut result = FoxAndHounds {
            move_no: 0,
            is_fox_next: fox_starts,
            fox_pos: Position(15),
            hounds_pos: [Position(82), Position(84), Position(86), Position(88)],
            free_squares: [false; 100],
            draw_with_colors: false,
        };
        result.reset_free_squares();
        result
    }

    pub fn new() -> FoxAndHounds {
        FoxAndHounds::new_fox_starts(true)
    }

    fn reset_free_squares(&mut self) {
        for i in 0..10 {
            for j in 0..10 {
                let idx = i * 10 + j;
                if i == 0 || i == 9 || j == 0 || j == 9 {
                    self.free_squares[idx] = false;
                } else {
                    self.free_squares[idx] = (i + j) % 2 == 0;
                }
            }
        }
        self.free_squares[self.fox_pos.0] = false;
        self.free_squares[self.hounds_pos[0].0] = false;
        self.free_squares[self.hounds_pos[1].0] = false;
        self.free_squares[self.hounds_pos[2].0] = false;
        self.free_squares[self.hounds_pos[3].0] = false;
    }

    fn check_hounds_move(&self, mov: &FHMove) {
        if mov.get_idx() > 3 {
            panic!("Illegal move {:?}, invalid index", mov);
        }
        let src = self.hounds_pos[mov.get_idx()];
        let dst = mov.get_dst();
        if self.fox_pos == dst
            || self.hounds_pos[0] == dst
            || self.hounds_pos[1] == dst
            || self.hounds_pos[2] == dst
            || self.hounds_pos[3] == dst
        {
            panic!("Illegal move {:?}, new position already occupied", mov);
        }
        if dst != src.pos_se() && dst != src.pos_sw() {
            panic!("Illegal move {:?}, hound cannot reach that square", mov);
        }
        if dst.get_y() < 1 || dst.get_y() > 8 || dst.get_x() < 1 || dst.get_x() > 8 {
            panic!("Illegal move {:?}, hound moves outside board", mov);
        }
    }

    fn check_fox_move(&self, mov: &FHMove) {
        if mov.get_idx() != 4 {
            panic!("Index not initialized correctly for fox move {:?}", mov);
        }
        let src = self.fox_pos;
        let dst = mov.get_dst();
        if self.hounds_pos[0] == dst
            || self.hounds_pos[1] == dst
            || self.hounds_pos[2] == dst
            || self.hounds_pos[3] == dst
        {
            panic!("Illegal move {:?}, new position already occupied", mov);
        }
        if dst != src.pos_ne() && dst != src.pos_nw() && dst != src.pos_se() && dst != src.pos_sw()
        {
            panic!("Illegal move {:?}, fox cannot reach that square", mov);
        }
        if dst.get_y() < 1 || dst.get_y() > 8 || dst.get_x() < 1 || dst.get_x() > 8 {
            panic!("Illegal move {:?}, fox moves outside board", mov);
        }
    }
}