Skip to main content

console_play_2/
console_play_2.rs

1use bitboard_xo::*;
2
3use std::error::Error;
4use std::io::{stdin, stdout, Write};
5
6/// try read a u8 from console
7fn read_u8() -> Result<u32, Box<dyn Error>> {
8    let mut user_input = String::new();
9    stdin().read_line(&mut user_input)?;
10    Ok(user_input.trim().parse()?)
11}
12
13/// prompt user for input to get xo position
14fn get_xo_pos() -> XOPos {
15    fn try_get_xo_pos() -> Result<XOPos, Box<dyn Error>> {
16        // prompt user and read row from console
17        print!("Input row : ");
18        stdout().flush()?;
19        let row = read_u8()?;
20
21        // prompt user and read col from console
22        print!("Input col : ");
23        stdout().flush()?;
24        let col = read_u8()?;
25
26        // parse row, col into XOPos
27        Ok(XOPos::row_col(row, col)?)
28    };
29
30    loop {
31        match try_get_xo_pos() {
32            Ok(xo_pos) => break xo_pos,
33            Err(err) => println!("{}", err),
34        }
35    }
36}
37
38fn main() -> Result<(), XOError> {
39    // create new XO game
40    let mut game = XO::new();
41
42    loop {
43        println!("{}", game);
44        // get position from user's input
45        let input_xo_pos = get_xo_pos();
46
47        // play at that position and match the returned game state
48        match game.play(input_xo_pos) {
49            // game end
50            Ok(Some(game_result)) => {
51                println!("{}", game);
52                println!("game result => {:?}", game_result);
53                break;
54            }
55            // game continue
56            Ok(None) => println!("game continue..."),
57            // some game error occurred
58            Err(xo_err) => println!("Error: {}", xo_err),
59        }
60    }
61
62    Ok(())
63}