summaryrefslogtreecommitdiff
path: root/tic_tac_toe/src/board.rs
diff options
context:
space:
mode:
authorKai Stevenson <kai@kaistevenson.com>2025-05-07 23:08:15 -0700
committerKai Stevenson <kai@kaistevenson.com>2025-05-07 23:08:15 -0700
commitaf2bc841119a6751c240dec95dd5511d4ee31d36 (patch)
tree693cb7d3d6d06bb667a89b1d4d8d2bdaee8ab983 /tic_tac_toe/src/board.rs
init ; most of tic tac toe done
Diffstat (limited to 'tic_tac_toe/src/board.rs')
-rw-r--r--tic_tac_toe/src/board.rs67
1 files changed, 67 insertions, 0 deletions
diff --git a/tic_tac_toe/src/board.rs b/tic_tac_toe/src/board.rs
new file mode 100644
index 0000000..5ad23ad
--- /dev/null
+++ b/tic_tac_toe/src/board.rs
@@ -0,0 +1,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],
+ };
+}