From 59c16f1749e5510ee4b48f4b581523f4b6914e3e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C3=ABl=20Hauspie?= <michael.hauspie@univ-lille.fr> Date: Sun, 27 Nov 2022 18:28:36 +0100 Subject: [PATCH] Add ConvertToString trait --- src/main.rs | 73 ++++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 55 insertions(+), 18 deletions(-) diff --git a/src/main.rs b/src/main.rs index c17d377..b03debf 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,9 +1,24 @@ +trait ConvertToString { + /// Returns a string representation of self + fn to_string(&self) -> String; +} + enum Square { Empty, Cross, Circle, } +impl ConvertToString for Square { + fn to_string(&self) -> String { + match self { + Square::Empty => String::from("."), + Square::Cross => String::from("X"), + Square::Circle => String::from("O"), + } + } +} + struct Board { board: [Square; 9], } @@ -14,8 +29,8 @@ impl Board { Self { board: [ Square::Empty, - Square::Cross, - Square::Circle, + Square::Empty, + Square::Empty, Square::Empty, Square::Empty, Square::Empty, @@ -28,25 +43,25 @@ impl Board { /// Display the board to standard output fn display(&self) { + println!("{}", self.to_string()); + } +} + +impl ConvertToString for Board { + fn to_string(&self) -> String { + let mut out = String::new(); for row in 0..3 { - println!( + out.push_str(format!( " {} | {} | {}", - square_to_char(&self.board[row * 3]), - square_to_char(&self.board[row * 3 + 1]), - square_to_char(&self.board[row * 3 + 2]) - ); + self.board[row * 3].to_string(), + self.board[row * 3 + 1].to_string(), + self.board[row * 3 + 2].to_string() + ).as_str()); if row == 0 || row == 1 { - println!("---+---+---"); + out.push_str("\n---+---+---\n"); } } - } -} - -fn square_to_char(s: &Square) -> char { - match s { - Square::Empty => '.', - Square::Cross => 'X', - Square::Circle => 'O', + out } } @@ -61,7 +76,7 @@ fn main() { // A module where the tests are located, more on modules later mod tests { use super::*; - + #[test] fn should_pass() { assert!(true); @@ -77,7 +92,6 @@ mod tests { let board = Board::new(); for square in board.board { - // Cannot do that due to 'trait' issues, more on that // later // assert_eq!(square, Square::Empty); @@ -87,4 +101,27 @@ mod tests { } } } + + #[test] + fn empty_board_to_string() { + let expected = " . | . | . +---+---+--- + . | . | . +---+---+--- + . | . | ."; + assert_eq!(expected, Board::new().to_string()); + } + + #[test] + fn empty_square_to_string_dot() { + assert_eq!(".", Square::Empty.to_string()); + } + #[test] + fn cross_square_to_string_x() { + assert_eq!("X", Square::Cross.to_string()); + } + #[test] + fn circle_square_to_string_big_o() { + assert_eq!("O", Square::Circle.to_string()); + } } -- GitLab