fours 0.1.0

Four in a row in your terminal, with three levels of opponent.
Documentation
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
use crate::game::BoardDimensions;
use crate::game::Cell;
use crate::game::GameError;
use crate::game::LINE_LENGTH;
use crate::game::Placement;
use crate::game::Player;
use crate::game::Status;
use crate::game::Victory;
use std::fmt;
use tudi::Bounded;
use tudi::Coordinate;
use tudi::Grid;
use tudi::GridError;

/// The four directions a winning line can run in, expressed as a single step along the line.
const LINE_STEPS: [Step; 4] = [
    Step::new(1, 0),
    Step::new(0, 1),
    Step::new(1, 1),
    Step::new(1, -1),
];

/// A valid position of a game of four in a row.
///
/// The state owns the board, the player to move and the [`Status`] of the game. Every method that
/// changes the state keeps all three consistent, so a state that exists is always a position that
/// can be reached by legal play.
///
/// The board is stored in an origin centered [`Grid`], where the lowest row and the leftmost
/// column can have negative coordinates. That layout does not leak out of this type: the public
/// API addresses the board with [`Cell`], whose columns and rows both start at zero.
///
/// # Textual board
///
/// [`Display`](fmt::Display) writes the board with the top row first, one line per row, using
/// [`Player::token`] for discs and `.` for empty cells.
///
/// ```
/// use fours::game::GameState;
///
/// let mut state = GameState::new();
/// state.apply_move(0).unwrap();
///
/// assert_eq!(
///     state.to_string(),
///     "\
/// .......
/// .......
/// .......
/// .......
/// .......
/// R......"
/// );
/// ```
#[derive(Debug)]
pub struct GameState {
    grid: Grid<Player>,
    current_player: Player,
    status: Status,
}

impl GameState {
    /// A state for an empty board of [`BoardDimensions::STANDARD`] size.
    pub fn new() -> Self {
        Self::with_dimensions(BoardDimensions::STANDARD)
    }

    /// A state for an empty board of the given size.
    pub fn with_dimensions(dimensions: BoardDimensions) -> Self {
        Self {
            grid: Grid::new(dimensions.column_count(), dimensions.row_count()),
            current_player: Player::FIRST,
            status: Status::InProgress,
        }
    }

    /// The size of the board.
    pub fn dimensions(&self) -> BoardDimensions {
        BoardDimensions::from_counts(self.column_count(), self.row_count())
    }

    /// The number of columns of the board.
    pub fn column_count(&self) -> usize {
        self.grid.x_count()
    }

    /// The number of rows of the board.
    pub fn row_count(&self) -> usize {
        self.grid.y_count()
    }

    /// The player whose turn it is.
    ///
    /// Once the game is over this keeps returning the player who made the final move.
    pub const fn current_player(&self) -> Player {
        self.current_player
    }

    /// How the game ended, or that it is still being played.
    pub const fn status(&self) -> &Status {
        &self.status
    }

    /// Whether the game ended, either in a win or in a draw.
    pub const fn is_over(&self) -> bool {
        self.status.is_over()
    }

    /// The winner, if the game was won.
    pub const fn winner(&self) -> Option<Player> {
        self.status.winner()
    }

    /// The number of discs on the board.
    pub fn disc_count(&self) -> usize {
        self.grid.iter_elements_new().count()
    }

    /// Whether every cell of the board holds a disc.
    pub fn is_full(&self) -> bool {
        self.disc_count() == self.dimensions().cell_count()
    }

    /// The disc at a cell, if the cell holds one.
    ///
    /// Cells outside the board are empty rather than an error, which keeps rendering code simple.
    pub fn piece_at(&self, cell: Cell) -> Option<Player> {
        let coordinate = self.coordinate_of(cell)?;
        self.player_at(coordinate)
    }

    /// Whether a disc can be placed in a column right now.
    pub fn is_playable(&self, column: usize) -> bool {
        !self.is_over() && self.landing_coordinate(column).is_ok()
    }

    /// The columns a disc can be placed in right now, in ascending order.
    pub fn legal_moves(&self) -> Vec<usize> {
        (0..self.column_count())
            .filter(|column| self.is_playable(*column))
            .collect()
    }

    /// The cell a disc would come to rest in if it were placed in a column.
    ///
    /// Returns [`None`] when the column cannot be played, either because the game is over, the
    /// column is full or the column is outside the board.
    pub fn landing_cell(&self, column: usize) -> Option<Cell> {
        if self.is_over() {
            return None;
        }

        let coordinate = self.landing_coordinate(column).ok()?;
        self.cell_of(coordinate)
    }

    /// Place a disc of the current player in a column and move the game forward.
    ///
    /// # Errors
    ///
    /// Returns [`GameError::GameOver`] if the game already ended,
    /// [`GameError::ColumnOutOfRange`] if the column is outside the board and
    /// [`GameError::ColumnFull`] if the column has no room left.
    ///
    /// # Examples
    ///
    /// ```
    /// use fours::game::Cell;
    /// use fours::game::GameState;
    ///
    /// let mut state = GameState::new();
    /// state.apply_move(2).unwrap();
    /// let placement = state.apply_move(2).unwrap();
    ///
    /// assert_eq!(placement.cell, Cell::new(2, 1));
    /// ```
    pub fn apply_move(&mut self, column: usize) -> Result<Placement, GameError> {
        if self.is_over() {
            return Err(GameError::GameOver);
        }

        let landing = self.landing_coordinate(column)?;
        let player = self.current_player;
        self.store(landing, player)?;

        let cell = self.cell_of(landing).ok_or(GameError::Board {
            reason: String::from("the disc landed outside the board"),
        })?;

        self.status = self.status_after(landing, player);
        if !self.is_over() {
            self.current_player = player.opponent();
        }

        Ok(Placement::new(player, cell))
    }

    /// The cell a disc would land in, walking up the column from the bottom.
    ///
    /// The walk relies entirely on the grid: an empty coordinate is where the disc lands, an
    /// occupied coordinate means the walk continues one step up and leaving the grid means the
    /// column is full.
    fn landing_coordinate(&self, column: usize) -> Result<Coordinate, GameError> {
        let mut candidate = Coordinate {
            x: self.column_to_x(column)?,
            y: self.grid.y_min_boundary(),
        };

        loop {
            match self.grid.element(&candidate) {
                Ok(_) => candidate.y += 1,
                Err(GridError::UnoccupiedError(_)) => return Ok(candidate),
                Err(GridError::OutOfBoundsError(_)) => {
                    return Err(GameError::ColumnFull { column });
                }
                Err(error) => {
                    return Err(GameError::Board {
                        reason: error.to_string(),
                    });
                }
            }
        }
    }

    fn store(&mut self, coordinate: Coordinate, player: Player) -> Result<(), GameError> {
        self.grid
            .store_element(&coordinate, player)
            .map(|_| ())
            .map_err(|error| GameError::Board {
                reason: error.to_string(),
            })
    }

    /// The status of the game after a player placed a disc at a coordinate.
    fn status_after(&self, coordinate: Coordinate, player: Player) -> Status {
        if let Some(line) = self.winning_line_through(coordinate, player) {
            Status::Won(Victory::new(player, line))
        } else if self.is_full() {
            Status::Draw
        } else {
            Status::InProgress
        }
    }

    /// The cells of the first line through a coordinate that is long enough to win.
    fn winning_line_through(&self, coordinate: Coordinate, player: Player) -> Option<Vec<Cell>> {
        LINE_STEPS.iter().find_map(|step| {
            let line = self.line_through(coordinate, *step, player);
            (line.len() >= LINE_LENGTH).then_some(line)
        })
    }

    /// Every connected disc of a player along a line through a coordinate.
    ///
    /// The line is read from one end to the other, so the cells come out in the order they sit on
    /// the board.
    fn line_through(&self, coordinate: Coordinate, step: Step, player: Player) -> Vec<Cell> {
        let mut current = self.far_end(coordinate, step.reversed(), player);
        let mut line = Vec::new();

        while self.player_at(current) == Some(player) {
            if let Some(cell) = self.cell_of(current) {
                line.push(cell);
            }
            current = step.applied_to(current);
        }

        line
    }

    /// The last disc of a player's line, walking in one direction from a coordinate.
    fn far_end(&self, from: Coordinate, step: Step, player: Player) -> Coordinate {
        let mut current = from;

        while self.player_at(step.applied_to(current)) == Some(player) {
            current = step.applied_to(current);
        }

        current
    }

    fn player_at(&self, coordinate: Coordinate) -> Option<Player> {
        self.grid.element(&coordinate).ok().copied()
    }

    fn column_to_x(&self, column: usize) -> Result<i32, GameError> {
        let offset = i32::try_from(column)
            .ok()
            .filter(|_| column < self.column_count());

        offset
            .map(|offset| self.grid.x_min_boundary() + offset)
            .ok_or(GameError::ColumnOutOfRange {
                column,
                column_count: self.column_count(),
            })
    }

    fn coordinate_of(&self, cell: Cell) -> Option<Coordinate> {
        if cell.column >= self.column_count() || cell.row >= self.row_count() {
            return None;
        }

        Some(Coordinate {
            x: self.grid.x_min_boundary() + i32::try_from(cell.column).ok()?,
            y: self.grid.y_min_boundary() + i32::try_from(cell.row).ok()?,
        })
    }

    /// Every cell of the board, from the top left to the bottom right.
    fn cells(&self) -> impl Iterator<Item = Cell> {
        let column_count = self.column_count();
        (0..self.row_count())
            .rev()
            .flat_map(move |row| (0..column_count).map(move |column| Cell::new(column, row)))
    }

    fn cell_of(&self, coordinate: Coordinate) -> Option<Cell> {
        let column = usize::try_from(coordinate.x - self.grid.x_min_boundary()).ok()?;
        let row = usize::try_from(coordinate.y - self.grid.y_min_boundary()).ok()?;
        let is_on_board = column < self.column_count() && row < self.row_count();

        is_on_board.then_some(Cell::new(column, row))
    }
}

impl Default for GameState {
    fn default() -> Self {
        Self::new()
    }
}

impl Clone for GameState {
    fn clone(&self) -> Self {
        let mut clone = Self::with_dimensions(self.dimensions());

        for (coordinate, player) in self.grid.iter_elements_new() {
            let stored = clone.grid.store_element(&coordinate, *player);
            debug_assert!(stored.is_ok(), "a clone has the bounds of its original");
        }
        clone.current_player = self.current_player;
        clone.status = self.status.clone();

        clone
    }
}

impl PartialEq for GameState {
    /// Two states are equal when they have the same board, the same player to move and the same
    /// status.
    fn eq(&self, other: &Self) -> bool {
        self.dimensions() == other.dimensions()
            && self.current_player == other.current_player
            && self.status == other.status
            && self
                .cells()
                .all(|cell| self.piece_at(cell) == other.piece_at(cell))
    }
}

impl Eq for GameState {}

impl fmt::Display for GameState {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        for (written, row) in (0..self.row_count()).rev().enumerate() {
            if written > 0 {
                formatter.write_str("\n")?;
            }

            for column in 0..self.column_count() {
                let symbol = self
                    .piece_at(Cell::new(column, row))
                    .map_or('.', Player::token);
                write!(formatter, "{symbol}")?;
            }
        }

        Ok(())
    }
}

/// A single step along one of the directions a winning line can run in.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct Step {
    x: i32,
    y: i32,
}

impl Step {
    const fn new(x: i32, y: i32) -> Self {
        Self { x, y }
    }

    const fn reversed(self) -> Self {
        Self::new(-self.x, -self.y)
    }

    const fn applied_to(self, coordinate: Coordinate) -> Coordinate {
        Coordinate {
            x: coordinate.x + self.x,
            y: coordinate.y + self.y,
        }
    }
}