summaryrefslogtreecommitdiff
path: root/tic_tac_toe/src/board.rs
blob: 5ad23ad66e2a763b0351410a1ef58332a701d840 (plain)
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
use std::fmt;

#[derive(Copy, Clone, PartialEq, Debug)]
pub enum Tile {
    PlayerOne,
    PlayerTwo,
    Unowned,
}

pub enum GameState {
    PlayerOneWin,
    PlayerTwoWin,
    Draw,
    InProgress,
}

impl fmt::Display for Tile {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let sym = match self {
            Tile::PlayerOne => "X",
            Tile::PlayerTwo => "O",
            Tile::Unowned => "_",
        };

        write!(f, "{sym}")
    }
}

pub type Coord = (usize, usize);

pub fn parse_coord(val: &str) -> Result<Coord, &'static str> {
    let split = val.split(",");

    let res: Vec<usize> = split
        .map(|v| v.trim().parse::<usize>().expect("Couldn't parse!"))
        .collect();

    if res.len() != 2 {
        return Err("Must provide exactly two dimensional coordinates");
    }

    if res[0] < 1 || res[0] > 3 || res[1] < 1 || res[1] > 3 {
        return Err("Coordinates must be between 1 and 3");
    }

    return Ok((res[0] - 1, res[1] - 1));
}

#[derive(Clone, Debug)]
pub struct Board {
    pub state: [[Tile; 3]; 3],
}

impl Board {
    pub fn get_at_coord(&self, coord: Coord) -> Tile {
        self.state[coord.0][coord.1]
    }
    pub fn set_at_coord(&mut self, coord: Coord, tile: Tile) -> () {
        self.state[coord.0][coord.1] = tile;
    }
}

pub fn init_board() -> Board {
    return Board {
        state: [[Tile::Unowned; 3]; 3],
    };
}