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

Refactor to make a board module with a tictactoe submodule

parent c678d964
No related branches found
No related tags found
No related merge requests found
//! A module that implements several board games
pub mod tictactoe;
#[derive(Clone, Copy, Debug, PartialEq)] #[derive(Clone, Copy, Debug, PartialEq)]
/// A Tictactoe square
pub enum Square { pub enum Square {
Empty, Empty,
Cross, Cross,
...@@ -16,11 +16,12 @@ impl std::fmt::Display for Square { ...@@ -16,11 +16,12 @@ impl std::fmt::Display for Square {
} }
} }
pub struct Board { /// A TicTacToe board
pub struct TicTacToe {
board: [Square; 9], board: [Square; 9],
} }
impl Board { impl TicTacToe {
/// Creates a new empty board /// Creates a new empty board
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
...@@ -34,13 +35,17 @@ impl Board { ...@@ -34,13 +35,17 @@ impl Board {
} }
} }
impl std::fmt::Display for Board { impl std::fmt::Display for TicTacToe {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(f, " A B C")?;
for row in 0..3 { for row in 0..3 {
writeln!(f, " {} | {} | {}", writeln!(
f,
" {} | {} | {} {}",
self.board[row * 3], self.board[row * 3],
self.board[row * 3 + 1], self.board[row * 3 + 1],
self.board[row * 3 + 2], self.board[row * 3 + 2],
row + 1,
)?; )?;
if row == 0 || row == 1 { if row == 0 || row == 1 {
writeln!(f, "---+---+---")?; writeln!(f, "---+---+---")?;
...@@ -56,7 +61,7 @@ mod tests { ...@@ -56,7 +61,7 @@ mod tests {
#[test] #[test]
fn new_board_squares_are_empty() { fn new_board_squares_are_empty() {
let board = Board::new(); let board = TicTacToe::new();
for square in board.board { for square in board.board {
assert_eq!(square, Square::Empty); assert_eq!(square, Square::Empty);
...@@ -65,13 +70,14 @@ mod tests { ...@@ -65,13 +70,14 @@ mod tests {
#[test] #[test]
fn empty_board_to_string() { fn empty_board_to_string() {
let expected = " . | . | . let expected = " A B C
. | . | . 1
---+---+--- ---+---+---
. | . | . . | . | . 2
---+---+--- ---+---+---
. | . | . . | . | . 3
"; ";
assert_eq!(expected, format!("{}", Board::new())); assert_eq!(expected, format!("{}", TicTacToe::new()));
} }
#[test] #[test]
...@@ -86,5 +92,4 @@ mod tests { ...@@ -86,5 +92,4 @@ mod tests {
fn circle_square_to_string_big_o() { fn circle_square_to_string_big_o() {
assert_eq!("O", format!("{}", Square::Circle)); assert_eq!("O", format!("{}", Square::Circle));
} }
} }
mod board; mod board;
use board::Board; use board::tictactoe::TicTacToe;
fn main() { fn main() {
let board = Board::new(); let board = TicTacToe::new();
board.display(); board.display();
} }
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment