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)]
/// A Tictactoe square
pub enum Square {
Empty,
Cross,
......@@ -16,11 +16,12 @@ impl std::fmt::Display for Square {
}
}
pub struct Board {
/// A TicTacToe board
pub struct TicTacToe {
board: [Square; 9],
}
impl Board {
impl TicTacToe {
/// Creates a new empty board
pub fn new() -> Self {
Self {
......@@ -34,14 +35,18 @@ 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 {
writeln!(f, " A B C")?;
for row in 0..3 {
writeln!(f, " {} | {} | {}",
self.board[row * 3],
self.board[row * 3 + 1],
self.board[row * 3 + 2],
)?;
writeln!(
f,
" {} | {} | {} {}",
self.board[row * 3],
self.board[row * 3 + 1],
self.board[row * 3 + 2],
row + 1,
)?;
if row == 0 || row == 1 {
writeln!(f, "---+---+---")?;
}
......@@ -53,10 +58,10 @@ impl std::fmt::Display for Board {
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn new_board_squares_are_empty() {
let board = Board::new();
let board = TicTacToe::new();
for square in board.board {
assert_eq!(square, Square::Empty);
......@@ -65,13 +70,14 @@ mod tests {
#[test]
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]
......@@ -86,5 +92,4 @@ mod tests {
fn circle_square_to_string_big_o() {
assert_eq!("O", format!("{}", Square::Circle));
}
}
mod board;
use board::Board;
use board::tictactoe::TicTacToe;
fn main() {
let board = Board::new();
let board = TicTacToe::new();
board.display();
}
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment