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
use std::ops::Not;

use takparse::{Color, Direction, Move, MoveKind, Pattern, Piece, Square};

use crate::{board::Board, error::PlayError, reserves::Reserves, stack::Stack};

#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct Game<const N: usize, const HALF_KOMI: i8> {
    pub board: Board<N>,
    pub to_move: Color,
    pub white_reserves: Reserves<N>,
    pub black_reserves: Reserves<N>,
    pub ply: u16,
    pub reversible_plies: u16,
}

impl<const N: usize, const HALF_KOMI: i8> Default for Game<N, HALF_KOMI>
where
    Reserves<N>: Default,
{
    fn default() -> Self {
        Self {
            board: Board::default(),
            to_move: Color::White,
            white_reserves: Reserves::default(),
            black_reserves: Reserves::default(),
            ply: u16::default(),
            reversible_plies: u16::default(),
        }
    }
}

impl<const N: usize, const HALF_KOMI: i8> Game<N, HALF_KOMI> {
    pub(crate) const fn is_swapped(&self) -> bool {
        self.ply < 2
    }

    pub(crate) fn color_to_place(&self) -> Color {
        if self.is_swapped() {
            self.to_move.not()
        } else {
            self.to_move
        }
    }

    pub(crate) fn get_reserves(&self) -> Reserves<N> {
        match self.color_to_place() {
            Color::White => self.white_reserves,
            Color::Black => self.black_reserves,
        }
    }

    fn dec_stones(&mut self) {
        if (self.to_move == Color::White) ^ self.is_swapped() {
            self.white_reserves.stones -= 1;
        } else {
            self.black_reserves.stones -= 1;
        }
    }

    fn dec_caps(&mut self) {
        match self.to_move {
            Color::White => self.white_reserves.caps -= 1,
            Color::Black => self.black_reserves.caps -= 1,
        }
    }

    /// Play a move on the board.
    ///
    /// # Errors
    ///
    /// In case the move is invalid an error is returned and the game
    /// might be in an invalid state.
    pub fn play(&mut self, my_move: Move) -> Result<(), PlayError> {
        match my_move.kind() {
            MoveKind::Place(piece) => self.execute_place(my_move.square(), piece),
            MoveKind::Spread(direction, pattern) => {
                self.execute_spread(my_move.square(), direction, pattern)
            }
        }?;
        self.update_reversible(my_move);
        self.ply += 1;
        self.to_move = self.to_move.not();
        Ok(())
    }

    fn execute_place(&mut self, square: Square, piece: Piece) -> Result<(), PlayError> {
        let Reserves { stones, caps } = self.get_reserves();
        let is_swapped = self.is_swapped();
        let color_to_place = self.color_to_place();
        let stack = self.board.get_mut(square).ok_or(PlayError::OutOfBounds)?;
        if !stack.is_empty() {
            Err(PlayError::AlreadyOccupied)
        } else if matches!(piece, Piece::Cap) && (caps == 0) {
            Err(PlayError::NoCapstone)
        } else if matches!(piece, Piece::Flat | Piece::Wall) && (stones == 0) {
            Err(PlayError::NoStones)
        } else if is_swapped && matches!(piece, Piece::Wall | Piece::Cap) {
            Err(PlayError::OpeningNonFlat)
        } else {
            *stack = Stack::new(piece, color_to_place);
            if matches!(piece, Piece::Flat | Piece::Wall) {
                self.dec_stones();
            } else {
                self.dec_caps();
            }
            Ok(())
        }
    }

    fn execute_spread(
        &mut self,
        square: Square,
        direction: Direction,
        pattern: Pattern,
    ) -> Result<(), PlayError> {
        let n = N as u8;

        let stack = self.board.get_mut(square).ok_or(PlayError::OutOfBounds)?;
        let (_, top_color) = stack.top().ok_or(PlayError::EmptySquare)?;
        if top_color != self.to_move {
            return Err(PlayError::StackNotOwned);
        }
        let mut amount = pattern.count_pieces();
        let (piece, colors) = stack.take::<N>(amount)?;
        let mut carry = colors.into_iter();

        // For each square in the spread, stack dropped pieces.
        let mut pos = square;
        for drop_count in pattern.drop_counts() {
            pos = pos
                .checked_step(direction, n)
                .ok_or(PlayError::SpreadOutOfBounds)?;

            for color in carry.by_ref().take(drop_count as usize) {
                amount -= 1;
                // unwrap is sound since we checked whether it is on the board earlier
                let Some(stack) = self.board.get_mut(pos) else {
                    continue;
                };
                stack.stack(if amount > 0 { Piece::Flat } else { piece }, color)?;
            }
        }

        assert_eq!(amount, 0);
        assert_eq!(carry.next(), None);
        Ok(())
    }

    fn update_reversible(&mut self, my_move: Move) {
        // TODO detect smashes
        if matches!(my_move.kind(), MoveKind::Place(_)) {
            self.reversible_plies = 0;
        } else {
            self.reversible_plies += 1;
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::{Game, PlayError, StackError, TakeError};

    #[test]
    fn square_out_of_bounds() {
        let mut game = Game::<5, 0>::default();
        let my_move = "a8".parse().unwrap();
        assert_eq!(game.play(my_move), Err(PlayError::OutOfBounds));
    }

    #[test]
    fn already_occupied() {
        let mut game = Game::<5, 0>::from_ptn_moves(&["a2"]);
        let my_move = "a2".parse().unwrap();
        assert_eq!(game.play(my_move), Err(PlayError::AlreadyOccupied));
    }

    #[test]
    fn no_capstone() {
        let mut game = Game::<6, 0>::from_ptn_moves(&["a1", "b1", "Ca2", "b2"]);
        let my_move = "Ca3".parse().unwrap();
        assert_eq!(game.play(my_move), Err(PlayError::NoCapstone));
    }

    #[test]
    fn no_stones() {
        let mut game = Game::<3, 0>::from_ptn_moves(&[
            "a1", "b1", "a2", "b2", "a2-", "a2", "b1<", "b1", "3a1>", "a1", "b1<", "c1", "3b1>",
            "b1", "2a1>", "a1", "3b1<", "b1", "c2", "c3",
        ]);
        // technically the game is over so maybe this should be an error?
        assert_eq!(game.play("c2<".parse().unwrap()), Ok(()));
        let my_move = "c2".parse().unwrap();
        assert_eq!(game.play(my_move), Err(PlayError::NoStones));
    }

    #[test]
    fn opening_wall() {
        let mut game = Game::<7, 0>::default();
        let my_move = "Sa1".parse().unwrap();
        assert_eq!(game.play(my_move), Err(PlayError::OpeningNonFlat));
    }

    #[test]
    fn opening_capstone() {
        let mut game = Game::<8, 0>::default();
        let my_move = "Ca1".parse().unwrap();
        assert_eq!(game.play(my_move), Err(PlayError::OpeningNonFlat));
    }

    #[test]
    fn empty_square() {
        let mut game = Game::<4, 0>::from_ptn_moves(&["a1", "b1", "a2"]);
        let my_move = "b2<".parse().unwrap();
        assert_eq!(game.play(my_move), Err(PlayError::EmptySquare));
    }

    #[test]
    fn stack_not_owned() {
        let mut game = Game::<5, 0>::from_ptn_moves(&[
            "a1", "e5", "c3", "b2", "c2", "c1", "d1", "Cd2", "b1", "c1+", "Cc1", "e2", "c1+",
        ]);
        let my_move = "3c2<12".parse().unwrap();
        assert_eq!(game.play(my_move), Err(PlayError::StackNotOwned));
    }

    #[test]
    fn spread_out_of_bounds() {
        let mut game = Game::<5, 0>::from_ptn_moves(&[
            "a1", "e5", "c3", "b2", "c2", "c1", "d1", "Cd2", "b1", "c1+", "Cc1", "e2", "c1+", "a2",
        ]);
        let my_move = "3c2-111".parse().unwrap();
        assert_eq!(game.play(my_move), Err(PlayError::SpreadOutOfBounds));
    }

    #[test]
    fn stack_on_wall() {
        let mut game = Game::<4, 0>::from_ptn_moves(&["a1", "a2", "Sb1"]);
        let my_move = "a1>".parse().unwrap();
        assert_eq!(
            game.play(my_move),
            Err(PlayError::StackError(StackError::Wall))
        );
    }

    #[test]
    fn stack_on_cap() {
        let mut game = Game::<7, 0>::from_ptn_moves(&["a1", "a2", "Cb1"]);
        let my_move = "a1>".parse().unwrap();
        assert_eq!(
            game.play(my_move),
            Err(PlayError::StackError(StackError::Cap))
        );
    }

    #[test]
    fn carry_limit() {
        let mut game =
            Game::<3, 0>::from_ptn_moves(&["a1", "b1", "b1<", "b1", "2a1>", "a1", "3b1<", "b1"]);
        let my_move = "4a1>".parse().unwrap();
        assert_eq!(
            game.play(my_move),
            Err(PlayError::TakeError(TakeError::CarryLimit))
        );
    }

    #[test]
    fn take_more_than_stack() {
        let mut game = Game::<3, 0>::from_ptn_moves(&["a1", "b1", "b1<", "b1"]);
        let my_move = "3a1>".parse().unwrap();
        assert_eq!(
            game.play(my_move),
            Err(PlayError::TakeError(TakeError::StackSize))
        );
    }
}