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
//! Implementation of Game Connect6
//!
//! It defines the game connect6 and provides the algorithm to find the winner.
//!
//! # Examples
//! ```rust
//! # extern crate connect6;
//! # use connect6::game::{Game, Player};
//! let mut game = Game::new();
//! let result = game.set((0, 0));
//! let winner = game.is_game_end();
//! assert_eq!(winner, Player::None);
//! ```
use game::Player;
use {Board, BOARD_SIZE};

use std::error;
use std::fmt;
use std::io;

#[cfg(test)]
mod tests;

/// Result of setting stone
#[derive(Debug, PartialEq)]
pub struct SetResult {
    pub player: Player,
    pub num_remain: i32,
    pub position: (usize, usize),
}

impl SetResult {
    /// Construct a new `SetResult`
    pub fn new() -> SetResult {
        SetResult {
            player: Player::None,
            num_remain: 0,
            position: (0, 0),
        }
    }

    /// Construct a `SetResult` with given game state and position.
    ///
    /// # Examples
    /// ```rust
    /// # extern crate connect6;
    /// # use connect6::game::{Game, Player, SetResult};
    /// let game = Game::new();
    /// let position = (0, 0);
    ///
    /// let play_result = SetResult::with_game(&game, position);
    /// let expected = SetResult{ player: Player::Black, num_remain: 1, position: (0, 0) };
    /// assert_eq!(play_result, expected);
    /// ```
    pub fn with_game(game: &Game, position: (usize, usize)) -> SetResult {
        SetResult {
            player: game.turn,
            num_remain: game.num_remain,
            position,
        }
    }
}

/// Error for invalid position of setting stone on game Connect6.
#[derive(Debug, Clone, Copy)]
struct InvalidPositionError {
    row: usize,
    col: usize,
}

impl fmt::Display for InvalidPositionError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "invalid position ({}, {})", self.row, self.col)
    }
}

impl error::Error for InvalidPositionError {
    fn description(&self) -> &str {
        "invalid position"
    }
}

/// Error for already set position on game Connect6.
#[derive(Debug, Clone, Copy)]
struct AlreadySetPositionError {
    row: usize,
    col: usize,
}

impl fmt::Display for AlreadySetPositionError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "already set position ({}, {})", self.row, self.col)
    }
}

impl error::Error for AlreadySetPositionError {
    fn description(&self) -> &str {
        "already set position"
    }
}

/// Implementation of Game Connect6
///
/// It defines the game connect6 with some visualization utilities.
///
/// # Examples
/// ```rust
/// # extern crate connect6;
/// # use connect6::game::{Game, Player};
/// let mut game = Game::new();
/// let result = game.set((0, 0));
/// game.print(&mut std::io::stdout()).unwrap();
///
/// let winner = game.is_game_end();
/// assert_eq!(winner, Player::None);
/// ```
pub struct Game {
    turn: Player,
    num_remain: i32,
    board: Board,
}

impl Game {
    /// Construct a new `Game`
    pub fn new() -> Game {
        Game {
            turn: Player::Black,
            num_remain: 1,
            board: [[Player::None; BOARD_SIZE]; BOARD_SIZE],
        }
    }

    /// Set the stone of current player with given position as zero-indexed (row, col).
    ///
    /// # Examples
    /// ```rust
    /// # extern crate connect6;
    /// # use connect6::game::{Game, Player, SetResult};
    /// let mut game = Game::new();
    /// let result = game.set((3, 4));
    /// let expected = SetResult{ player: Player::Black, num_remain: 0, position: (3, 4) };
    /// assert_eq!(result.unwrap(), expected);
    /// ```
    ///
    /// # Errors
    /// 1. If given position out of board.
    /// 2. If other stone place already in given position.
    pub fn set(&mut self, pos: (usize, usize)) -> Result<SetResult, Box<error::Error + Send>> {
        let (row, col) = pos;
        // position param validation
        if row >= BOARD_SIZE || col >= BOARD_SIZE {
            return Err(Box::new(InvalidPositionError { row, col }));
        }
        // in-board validation
        if self.board[row][col] != Player::None {
            return Err(Box::new(AlreadySetPositionError { row, col }));
        }
        self.board[row][col] = self.turn;

        self.num_remain -= 1;
        let result = SetResult::with_game(self, pos);

        // if turn end, switch player
        if self.num_remain <= 0 {
            self.num_remain = 2;
            self.turn.mut_switch();
        }
        Ok(result)
    }

    /// Return board
    pub fn get_board(&self) -> &Board {
        &self.board
    }

    /// Return current player
    pub fn get_turn(&self) -> Player {
        self.turn
    }

    /// Return num_remain
    pub fn get_remain(&self) -> i32 {
        self.num_remain
    }

    /// Print the board status
    ///
    /// # Examples
    /// ```rust
    /// # extern crate connect6;
    /// # use connect6::game::Game;
    /// let mut game = Game::new();
    /// let result = game.set((3, 4)).unwrap(); // black
    /// let result = game.set((3, 3)).unwrap(); // white
    ///
    /// game.print(&mut std::io::stdout());
    /// ```
    /// Expected results
    /// ```ignore
    /// 0 A B C D E F G H I J K L M N O
    /// a _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
    /// b _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
    /// c _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
    /// d _ _ _ O X _ _ _ _ _ _ _ _ _ _
    /// e _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
    /// f _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
    /// g _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
    /// h _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
    /// i _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
    /// j _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
    /// k _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
    /// l _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
    /// m _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
    /// n _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
    /// o _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
    /// ```
    pub fn print(&self, writer: &mut io::Write) -> io::Result<usize> {
        // generate ascii canvas
        let mut paint = Paint::new(writer);
        paint.push(b"0 A B C D E F G H I J K L M N O\n");

        for i in 0..BOARD_SIZE {
            let row_name = [0x61 + i as u8, ' ' as u8];
            paint.push(&row_name);

            for j in 0..BOARD_SIZE {
                match self.board[i][j] {
                    Player::Black => paint.push(b"X "),
                    Player::White => paint.push(b"O "),
                    Player::None => paint.push(b"_ "),
                }
            }
            paint.push_one('\n' as u8);
        }
        // make output to writer
        paint.write()
    }

    /// Return game winner if game end, else Player::None
    ///
    /// # Examples
    /// ```rust
    /// # extern crate connect6;
    /// # use connect6::game::{Game, Player};
    /// let mut game = Game::new();
    /// game.set((3, 4)).unwrap();
    /// assert_eq!(game.is_game_end(), Player::None);
    /// ```
    pub fn is_game_end(&self) -> Player {
        use super::search_winner::search;
        search(&self.board)
    }
}

/// Simple ascii buffer
///
/// # Examples
///```rust
/// # extern crate connect6;
/// # use connect6::game::Paint;
/// let mut stdout = std::io::stdout();
/// let mut paint = Paint::new(&mut stdout);
/// paint.push(b"ABC");
/// paint.push_one('\n' as u8);
/// paint.write();
/// ```
/// Expected results
/// ```ignore
/// ABC
/// ```
pub struct Paint<'a> {
    vec: Vec<u8>,
    writer: &'a mut io::Write,
}

impl<'a> Paint<'a> {
    /// Construct a new `Paint`.
    ///
    /// # Examples
    /// ```rust
    /// # extern crate connect6;
    /// # use connect6::game::Paint;
    /// let mut stdout = std::io::stdout();
    /// let mut paint = Paint::new(&mut stdout);
    /// ```
    pub fn new(writer: &'a mut io::Write) -> Paint<'a> {
        Paint {
            vec: Vec::new(),
            writer,
        }
    }

    /// Push a byte slice to the buffer
    ///
    /// # Examples
    /// ```rust
    /// # extern crate connect6;
    /// # use connect6::game::Paint;
    /// let mut stdout = std::io::stdout();
    /// let mut paint = Paint::new(&mut stdout);
    /// paint.push(b"ABC");
    /// ```
    pub fn push(&mut self, data: &[u8]) {
        for elem in data {
            self.vec.push(*elem);
        }
    }

    /// Push a single u8 to the buffer
    ///
    /// # Examples
    /// ```rust
    /// # extern crate connect6;
    /// # use connect6::game::Paint;
    /// let mut stdout = std::io::stdout();
    /// let mut paint = Paint::new(&mut stdout);
    /// paint.push_one('\n' as u8);
    /// ```
    pub fn push_one(&mut self, data: u8) {
        self.vec.push(data);
    }

    /// Write buffer to the io stream
    ///
    /// # Examples
    /// ```rust
    /// # extern crate connect6;
    /// # use connect6::game::Paint;
    /// let mut stdout = std::io::stdout();
    /// let mut paint = Paint::new(&mut stdout);
    /// paint.push(b"ABC");
    /// paint.push_one('\n' as u8);
    /// paint.write();
    /// ```
    /// Expected results
    /// ```ignore
    /// ABC
    /// ```
    pub fn write(&mut self) -> io::Result<usize> {
        self.writer.write(&self.vec[..])
    }
}