Skip to content
Snippets Groups Projects
Commit 9e981954 authored by Michael Hauspie's avatar Michael Hauspie
Browse files

Implement Board trait for TicTacToe board

parent 025d6e85
No related branches found
No related tags found
No related merge requests found
use std::str::FromStr;
#[derive(Clone, Copy, Debug, PartialEq)] #[derive(Clone, Copy, Debug, PartialEq)]
pub enum Player { pub enum Player {
Cross, Cross,
...@@ -35,6 +37,7 @@ pub struct Board { ...@@ -35,6 +37,7 @@ pub struct Board {
} }
/// A TicTacToe Move /// A TicTacToe Move
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Move { pub enum Move {
A1 = 0, A1 = 0,
B1 = 1, B1 = 1,
...@@ -47,10 +50,16 @@ pub enum Move { ...@@ -47,10 +50,16 @@ pub enum Move {
C3 = 8, C3 = 8,
} }
// impl std::fmt::FromStr for Move {
// }
impl Board { impl Board {
/// Creates a new empty board /// Creates a new empty board
pub fn new() -> Self { pub fn new() -> Self {
Self { board: [Square::Empty; 9] } Self {
board: [Square::Empty; 9],
}
} }
/// Display the board to standard output /// Display the board to standard output
...@@ -79,6 +88,45 @@ impl std::fmt::Display for Board { ...@@ -79,6 +88,45 @@ impl std::fmt::Display for Board {
} }
} }
// Implementations of the Board trait for Tictactoe
impl super::Board<Move, Player> for Board {
/// Apply a move to the board
fn do_move(&mut self, turn: Player, m: &Move) {
let idx = *m as usize;
if self.board[idx] == Square::Empty {
self.board[idx] = Square::Full(turn);
}
}
/// Returns if a given player has won the game considering this
/// board
fn has_won(&self, player: Player) -> bool {
for (s1, s2, s3) in [
// rows
(0, 1, 2),
(3, 4, 5),
(6, 7, 8),
// columns
(0, 3, 6),
(1, 4, 7),
(2, 5, 8),
// diagonals
(0, 4, 8),
(2, 4, 6),
] {
if (
Square::Full(player),
Square::Full(player),
Square::Full(player),
) == (self.board[s1], self.board[s2], self.board[s3])
{
return true;
}
}
return false;
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment