From d906586bf36638b220ab1a2849a9482393779e1e Mon Sep 17 00:00:00 2001 From: a14m Date: Thu, 8 Apr 2021 00:48:44 +0200 Subject: Add the Display trait implementation to allow rendering --- CLI/rust/src/game_of_life/simulation/universe.rs | 70 +++++++++++++++++++++++- 1 file changed, 69 insertions(+), 1 deletion(-) 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>, } +/// 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 for Universe { type Output = Plane; fn index(&self, idx: isize) -> &Plane { -- cgit v1.2.3