diff options
| author | a14m <[email protected]> | 2021-04-08 00:48:44 +0200 |
|---|---|---|
| committer | a14m <[email protected]> | 2021-04-08 00:48:44 +0200 |
| commit | d906586bf36638b220ab1a2849a9482393779e1e (patch) | |
| tree | 19acff24030c10a389455c80b2ae93d7dcddca76 | |
| parent | bc23a70a08810f03e5b9584f54bafc1c336759cd (diff) | |
Add the Display trait implementation to allow rendering
| -rw-r--r-- | CLI/rust/src/game_of_life/simulation/universe.rs | 70 |
1 files changed, 69 insertions, 1 deletions
diff --git a/CLI/rust/src/game_of_life/simulation/universe.rs b/CLI/rust/src/game_of_life/simulation/universe.rs index 69d8f67..dab1915 100644 --- a/CLI/rust/src/game_of_life/simulation/universe.rs +++ b/CLI/rust/src/game_of_life/simulation/universe.rs @@ -1,7 +1,7 @@ use super::circular_index; use crate::game_of_life::opts::Opts; use crate::game_of_life::simulation::plane::Plane; -use std::ops::Index; +use std::{fmt, ops::Index}; /// Game of Life universe struct for running simulations #[derive(Debug, Clone, PartialEq)] @@ -11,6 +11,74 @@ pub(crate) struct Universe { pub future: Plane<Plane<bool>>, } +/// Implement print for the universe +impl fmt::Display for Universe { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let mut to_s = String::new(); + for row in 0..self.current.len() { + for col in 0..self.current[row].len() { + match self[row as isize][col as isize] { + true => to_s.push(self.opts.live_cell), + false => to_s.push(self.opts.dead_cell), + }; + } + to_s.push_str("\n"); + } + to_s.push_str(&format!("{}", self.opts.banner())); + write!(f, "{}", to_s) + } +} + +#[cfg(test)] +mod display { + use super::*; + + fn universe(opts: Opts) -> Universe { + Universe { + opts, + current: Plane(vec![ + Plane(vec![false; 5]), + Plane(vec![false, true, true, true, false]), + Plane(vec![false; 5]), + ]), + future: Plane(vec![Plane(vec![])]), + } + } + + #[test] + fn without_input() { + let opts = Opts { + input: None, + seed: 1337, + width: 13, + height: 13, + live_cell: 'L', + dead_cell: 'D', + delay: 13, + }; + + let universe = universe(opts); + assert_eq!(universe.to_string(), "DDDDD\nDLLLD\nDDDDD\nSeed: 1337") + } + + #[test] + fn with_input() { + let opts = Opts { + input: Some(String::from("http://example.com")), + seed: 1337, + width: 13, + height: 13, + live_cell: 'X', + dead_cell: '.', + delay: 13, + }; + + let universe = universe(opts); + assert_eq!(universe.to_string(), ".....\n.XXX.\n.....\nInput: http://example.com") + } + +} + impl Index<isize> for Universe { type Output = Plane<bool>; fn index(&self, idx: isize) -> &Plane<bool> { |
